#!/usr/bin/env python3 """šŸƒā€ā™‚ļø Comprehensive Garmin Connect API Demo. ========================================== This is a comprehensive demonstration program showing ALL available API calls and error handling patterns for python-garminconnect. For a simple getting-started example, see example.py Dependencies: pip3 install requests readchar Environment Variables (optional): export GARMIN_EMAIL= export GARMIN_PASSWORD= export GARMINTOKENS= """ import datetime import html import json import logging import os import re import sys import time from contextlib import suppress from datetime import timedelta from getpass import getpass from pathlib import Path from typing import Any import readchar import requests from garminconnect import ( Garmin, GarminConnectAuthenticationError, GarminConnectConnectionError, GarminConnectNotFoundError, GarminConnectTooManyRequestsError, parse_activity_detail_metrics, ) from garminconnect.client import token_file_path # Debug mode: enable with --debug / -d CLI flag or DEMO_DEBUG=1 env var. # When active, shows timestamped DEBUG logs from garminconnect and the # underlying HTTP stack (urllib3 / requests) so you can see where delays come # from. Also consumes the flag from sys.argv so downstream code doesn't see it. _DEBUG = bool(os.getenv("DEMO_DEBUG")) or any(a in sys.argv for a in ("-d", "--debug")) for _flag in ("-d", "--debug"): while _flag in sys.argv: sys.argv.remove(_flag) if _DEBUG: logging.basicConfig( level=logging.DEBUG, format="%(asctime)s.%(msecs)03d %(levelname)s %(name)s: %(message)s", datefmt="%H:%M:%S", ) for _name in ( "garminconnect", "urllib3", "urllib3.connectionpool", "requests", ): logging.getLogger(_name).setLevel(logging.DEBUG) else: # Quiet known-noisy library errors to avoid double error messages logging.getLogger("garminconnect").setLevel(logging.CRITICAL) _LOGGER = logging.getLogger("demo") def _open_private(path: str | Path, mode: str, encoding: str | None = None): """Open a new or existing export file with owner-only permissions.""" if mode not in {"w", "wb"}: raise ValueError(f"Unsupported private file mode: {mode}") flags = os.O_WRONLY | os.O_CREAT | os.O_TRUNC if hasattr(os, "O_NOFOLLOW"): flags |= os.O_NOFOLLOW fd = os.open(Path(path), flags, 0o600) try: if hasattr(os, "fchmod"): os.fchmod(fd, 0o600) if "b" in mode: return os.fdopen(fd, mode) return os.fdopen(fd, mode, encoding=encoding or "utf-8") except Exception: os.close(fd) raise def _html(value: Any) -> str: """Escape data returned by Garmin before inserting it into HTML.""" return html.escape(str(value), quote=True) def _safe_filename_component(value: Any) -> str: """Convert account-provided text into a single safe filename component.""" component = re.sub(r"[^\w .-]", "_", str(value), flags=re.UNICODE).strip(" .") return component[:120] or "export" def safe_readkey() -> str: """Safe wrapper around readchar.readkey() that handles non-TTY environments. This is particularly useful on macOS and in CI/CD environments where stdin might not be a TTY, which would cause readchar to fail with: termios.error: (25, 'Inappropriate ioctl for device') Returns: str: A single character input from the user """ if not sys.stdin.isatty(): print("WARNING: stdin is not a TTY. Falling back to input().") user_input = input("Enter a key (then press Enter): ") return user_input[0] if user_input else "" try: return readchar.readkey() except Exception as e: print(f"readkey() failed: {e}") user_input = input("Enter a key (then press Enter): ") return user_input[0] if user_input else "" class Config: """Configuration class for the Garmin Connect API demo.""" def __init__(self): # The logged-in client, set by main(); today follows its profile timezone. self.api: Garmin | None = None # Load environment variables self.email = os.getenv("GARMIN_EMAIL") or os.getenv("EMAIL") self.password = os.getenv("GARMIN_PASSWORD") or os.getenv("PASSWORD") self.tokenstore = os.getenv("GARMINTOKENS") or "~/.garminconnect" # API call settings self.default_limit = 100 self.start = 0 self.start_badge = 1 # Badge, challenge and goal calls start counting at 1 # Activity settings self.activityfile = "test_data/*.gpx" # Supported file types: .fit .gpx .tcx self.workoutfile = "test_data/sample_workout.json" # Sample workout JSON file # Export settings self.export_dir = Path("your_data") self.export_dir.mkdir(mode=0o700, exist_ok=True) if os.name != "nt": self.export_dir.chmod(0o700) # Dates are evaluated on every access (not once at startup) so a long # running session never lags behind midnight, and once logged in they # follow the user's Garmin profile timezone rather than the machine clock. @property def today(self) -> datetime.date: if self.api is not None and self.api.display_name: try: return self.api.today() except Exception as e: _LOGGER.debug("Falling back to machine date: %s", e) return datetime.date.today() @property def week_start(self) -> datetime.date: return self.today - timedelta(days=7) @property def month_start(self) -> datetime.date: return self.today - timedelta(days=30) # Initialize configuration config = Config() # Organized menu categories menu_categories = { "1": { "name": "šŸ‘¤ User & Profile", "options": { "1": {"desc": "Get full name", "key": "get_full_name"}, "2": {"desc": "Get unit system", "key": "get_unit_system"}, "3": {"desc": "Get user profile", "key": "get_user_profile"}, "4": { "desc": "Get userprofile settings", "key": "get_userprofile_settings", }, "5": { "desc": "Personal information (timezone, biometrics)", "key": "get_personal_information", }, "6": {"desc": "User profile base", "key": "get_user_profile_base"}, "7": {"desc": "Privacy settings", "key": "get_privacy_settings"}, "8": {"desc": "Account usage indicators", "key": "get_usage_indicators"}, }, }, "2": { "name": "šŸ“Š Daily Health & Activity", "options": { "1": { "desc": "Get activity data for '{today}'", "key": "get_stats", }, "2": { "desc": "Get user summary for '{today}'", "key": "get_user_summary", }, "3": { "desc": "Get stats and body composition for '{today}'", "key": "get_stats_and_body", }, "4": { "desc": "Get steps data for '{today}'", "key": "get_steps_data", }, "5": { "desc": "Get heart rate data for '{today}'", "key": "get_heart_rates", }, "6": { "desc": "Get resting heart rate from '{week_start}' to '{today}'", "key": "get_rhr_daily", }, "7": { "desc": "Get daily sleep summaries from '{week_start}' to '{today}'", "key": "get_sleep_daily", }, "8": { "desc": "Get stress data for '{today}'", "key": "get_all_day_stress", }, "9": { "desc": "Get lifestyle logging data for '{today}'", "key": "get_lifestyle_logging_data", }, "a": { "desc": "Get daily calories from '{week_start}' to '{today}'", "key": "get_calories_daily", }, "0": { "desc": "SpO2 with acclimation for today", "key": "get_spo2_acclimation_data", }, "b": {"desc": "Daily movement chart", "key": "get_daily_movement"}, "c": {"desc": "Step goal (device vs user)", "key": "get_steps_goal"}, "d": {"desc": "Last device sync timestamp", "key": "get_sync_timestamp"}, "e": { "desc": "Hourly intensity minutes for today", "key": "get_hourly_intensity_minutes", }, "f": {"desc": "Sleep for today (sleep-service)", "key": "get_daily_sleep"}, "g": {"desc": "Naps for today", "key": "get_naps"}, "h": {"desc": "Blood pressure for today", "key": "get_blood_pressure_day"}, "i": { "desc": "Hydration: intake, goal, containers", "key": "get_hydration_all_data", }, "j": { "desc": "Week average resting heart rate", "key": "get_week_average_resting_hr", }, "k": {"desc": "Fitness age details (v2)", "key": "get_fitness_age_details"}, }, }, "3": { "name": "šŸ”¬ Advanced Health Metrics", "options": { "1": { "desc": "Get training readiness for '{today}'", "key": "get_training_readiness", }, "2": { "desc": "Get morning training readiness for '{today}'", "key": "get_morning_training_readiness", }, "3": { "desc": "Get training status for '{today}'", "key": "get_training_status", }, "4": { "desc": "Get respiration data for '{today}'", "key": "get_respiration_data", }, "5": { "desc": "Get SpO2 data for '{today}'", "key": "get_spo2_data", }, "6": { "desc": "Get max metrics (VO2, fitness age) from '{week_start}' to '{today}'", "key": "get_max_metrics_range", }, "7": { "desc": "Get Heart Rate Variability (HRV) from '{week_start}' to '{today}'", "key": "get_hrv_data_range", }, "8": { "desc": "Get Fitness Age data for '{today}'", "key": "get_fitnessage_data", }, "9": { "desc": "Get stress data for '{today}'", "key": "get_stress_data", }, "0": {"desc": "Get lactate threshold data", "key": "get_lactate_threshold"}, "a": { "desc": "Get intensity minutes for '{today}'", "key": "get_intensity_minutes_data", }, "b": { "desc": "Get running tolerance from '{week_start}' to '{today}'", "key": "get_running_tolerance", }, "c": { "desc": "Get configured heart rate zones", "key": "get_heart_rate_zones", }, "d": { "desc": "Get configured power zones for all sports", "key": "get_power_zones", }, "e": { "desc": "Get configured cycling power zones", "key": "get_power_zones_for_sport", }, "f": { "desc": "Get functional threshold power range from '{week_start}' to '{today}'", "key": "get_functional_threshold_power_range", }, "g": { "desc": "Get four-week training load balance for '{today}'", "key": "get_training_four_week_load_balance", }, "h": { "desc": "Get daily training status (acute/chronic load) for '{today}'", "key": "get_daily_training_status", }, "i": { "desc": "Get activity training load from '{month_start}' to '{today}'", "key": "get_training_load_activities", }, "j": {"desc": "Latest VO2 max record", "key": "get_max_metrics_latest"}, "k": { "desc": "Training readiness, last 7 days", "key": "get_training_readiness_range", }, "l": { "desc": "Weekly training status, last 30 days", "key": "get_weekly_training_status", }, "m": { "desc": "Heat & altitude acclimation (latest)", "key": "get_heat_altitude_acclimation", }, "n": { "desc": "Heat & altitude acclimation, last 7 days", "key": "get_heat_altitude_acclimation_range", }, "o": {"desc": "Cycling ability (latest)", "key": "get_cycling_ability"}, "p": { "desc": "Cycling ability, last 30 days", "key": "get_cycling_ability_range", }, "r": {"desc": "Running economy (latest)", "key": "get_running_economy"}, "s": {"desc": "Stamina curve (running)", "key": "get_stamina_curve"}, "t": { "desc": "Power curve, last 30 days (cycling)", "key": "get_power_curve", }, "u": { "desc": "Critical swim speed (latest)", "key": "get_critical_swim_speed", }, "v": {"desc": "Heart rate zones (v2)", "key": "get_heart_rate_zones_v2"}, "w": { "desc": "Biometric statistics, last 7 days", "key": "get_biometric_stats", }, "x": { "desc": "Power-to-weight history, last 30 days", "key": "get_power_to_weight_range", }, "y": { "desc": "Current biometrics (VO2 max, LT, FTP)", "key": "get_current_biometrics", }, "z": {"desc": "Glucose readings for today", "key": "get_glucose_data"}, }, }, "4": { "name": "šŸ“ˆ Historical Data & Trends", "options": { "1": { "desc": "Get daily steps from '{week_start}' to '{today}'", "key": "get_daily_steps", }, "2": { "desc": "Get body battery from '{week_start}' to '{today}'", "key": "get_body_battery", }, "3": { "desc": "Get floors data for '{week_start}'", "key": "get_floors", }, "4": { "desc": "Get blood pressure from '{week_start}' to '{today}'", "key": "get_blood_pressure", }, "5": { "desc": "Get progress summary from '{week_start}' to '{today}'", "key": "get_progress_summary_between_dates", }, "6": { "desc": "Get body battery events for '{week_start}'", "key": "get_body_battery_events", }, "7": { "desc": "Get weekly steps (52 weeks ending '{today}')", "key": "get_weekly_steps", }, "8": { "desc": "Get weekly stress (52 weeks ending '{today}')", "key": "get_weekly_stress", }, "9": { "desc": "Get weekly intensity minutes from '{week_start}' to '{today}'", "key": "get_weekly_intensity_minutes", }, "0": { "desc": "Daily steps stats with aggregations, last 7 days", "key": "get_daily_stats", }, "a": { "desc": "Daily heart rate stats, last 7 days", "key": "get_daily_heart_rate_stats", }, "b": { "desc": "Weekly heart rate stats, last 12 weeks", "key": "get_weekly_heart_rate_stats", }, "c": { "desc": "Daily stress stats, last 7 days", "key": "get_daily_stress_stats", }, "d": { "desc": "Daily Body Battery stats, last 7 days", "key": "get_daily_body_battery_stats", }, "e": { "desc": "Daily intensity minutes, last 7 days", "key": "get_daily_intensity_minutes_stats", }, "f": { "desc": "Daily respiration stats, last 7 days", "key": "get_daily_respiration_stats", }, "g": { "desc": "Daily floors stats, last 7 days", "key": "get_daily_floors_stats", }, "h": { "desc": "Weekly calories, last 12 weeks", "key": "get_weekly_calories_stats", }, "i": {"desc": "Monthly steps, last 6 months", "key": "get_monthly_steps"}, "j": { "desc": "Average steps and resting HR, last 7 days", "key": "get_stats_averages", }, "k": {"desc": "Lifetime totals", "key": "get_lifetime_totals"}, "l": { "desc": "Daily summaries, last 7 days (one call)", "key": "get_daily_summaries", }, "m": { "desc": "Weekly sleep statistics, last 12 weeks", "key": "get_sleep_stats_weekly", }, "n": { "desc": "Overall sleep statistics, last 30 days", "key": "get_sleep_stats_overall", }, "o": { "desc": "Health Snapshot sessions, last 30 days", "key": "get_health_snapshots_range", }, "p": { "desc": "Fitness age, daily, last 7 days", "key": "get_fitness_age_daily", }, "r": { "desc": "Fitness age, weekly, last 12 weeks", "key": "get_fitness_age_weekly", }, "s": { "desc": "Available progress metrics, last 30 days", "key": "get_available_metrics", }, "t": {"desc": "One-rep-max estimates (strength)", "key": "get_one_rep_max"}, }, }, "5": { "name": "šŸƒ Activities & Workouts", "options": { "1": { "desc": f"Get recent activities (limit {config.default_limit})", "key": "get_activities", }, "2": {"desc": "Get last activity", "key": "get_last_activity"}, "3": { "desc": "Get activities for today '{today}'", "key": "get_activities_fordate", }, "4": { "desc": "Download activities by date range '{week_start}' to '{today}'", "key": "download_activities", }, "5": { "desc": "Get all activity types and statistics", "key": "get_activity_types", }, "6": { "desc": f"Upload activity data from {config.activityfile}", "key": "upload_activity", }, "7": {"desc": "Get workouts", "key": "get_workouts"}, "8": {"desc": "Get activity splits (laps)", "key": "get_activity_splits"}, "9": { "desc": "Get activity typed splits", "key": "get_activity_typed_splits", }, "0": { "desc": "Get activity split summaries", "key": "get_activity_split_summaries", }, "a": {"desc": "Get activity weather data", "key": "get_activity_weather"}, "b": { "desc": "Get activity heart rate zones", "key": "get_activity_hr_in_timezones", }, "c": { "desc": "Get activity power zones", "key": "get_activity_power_in_timezones", }, "d": { "desc": "Get cycling FTP (Functional Threshold Power)", "key": "get_cycling_ftp", }, "e": { "desc": "Get detailed activity information", "key": "get_activity_details", }, "f": {"desc": "Get activity gear information", "key": "get_activity_gear"}, "g": {"desc": "Get single activity data", "key": "get_activity"}, "h": { "desc": "Get strength training exercise sets", "key": "get_activity_exercise_sets", }, "i": {"desc": "Get workout by ID", "key": "get_workout_by_id"}, "j": {"desc": "Download workout to .FIT file", "key": "download_workout"}, "k": { "desc": f"Upload workout from {config.workoutfile}", "key": "upload_workout", }, "l": { "desc": "Get activities by date range '{today}'", "key": "get_activities_by_date", }, "m": {"desc": "Set activity name", "key": "set_activity_name"}, "n": {"desc": "Set activity type", "key": "set_activity_type"}, "o": {"desc": "Create manual activity", "key": "create_manual_activity"}, "p": {"desc": "Delete activity", "key": "delete_activity"}, "r": { "desc": "Count activities for current user", "key": "count_activities", }, "s": { "desc": "Schedule a workout on a date (interactive)", "key": "scheduled_workout", }, "t": { "desc": f"Import activity (no Strava re-export) from {config.activityfile}", "key": "import_activity", }, "u": { "desc": "Get scheduled workouts by year and month", "key": "get_scheduled_workouts", }, "v": { "desc": "Upload typed running workout (sample)", "key": "upload_running_workout", }, "w": { "desc": "Upload typed cycling workout (sample)", "key": "upload_cycling_workout", }, "x": { "desc": "Upload typed swimming workout (sample)", "key": "upload_swimming_workout", }, "A": { "desc": "Get activities filtered by type/subtype (interactive)", "key": "get_activities_filtered", }, "B": { "desc": "Get the earliest upcoming scheduled workout (today or later)", "key": "get_next_scheduled_workout", }, "C": { "desc": "Get photos attached to an activity (interactive)", "key": "get_activity_images", }, "D": { "desc": "Upload typed swimming workout with CSS offset targets (sample)", "key": "upload_swimming_css_workout", }, }, }, "6": { "name": "āš–ļø Body Composition & Weight", "options": { "1": { "desc": "Get body composition for '{today}'", "key": "get_body_composition", }, "2": { "desc": "Get weigh-ins from '{week_start}' to '{today}'", "key": "get_weigh_ins", }, "3": { "desc": "Get daily weigh-ins for '{today}'", "key": "get_daily_weigh_ins", }, "4": {"desc": "Add a weigh-in (interactive)", "key": "add_weigh_in"}, "5": { "desc": "Add body composition for '{today}' (interactive)", "key": "add_body_composition", }, "6": { "desc": "Delete all weigh-ins for '{today}'", "key": "delete_weigh_ins", }, "7": {"desc": "Delete specific weigh-in", "key": "delete_weigh_in"}, "8": {"desc": "Latest weigh-in", "key": "get_latest_weight"}, "9": {"desc": "First weigh-in ever", "key": "get_first_weight"}, "0": { "desc": "Last weigh-in per day, last 30 days", "key": "get_daily_last_weight", }, "a": {"desc": "Weekly weight, last 52 weeks", "key": "get_weekly_weight"}, }, }, "7": { "name": "šŸ† Goals & Achievements", "options": { "1": { "desc": "Get personal records (decodes running typeId, interactive)", "key": "get_personal_records", }, "2": {"desc": "Get earned badges", "key": "get_earned_badges"}, "3": {"desc": "Get adhoc challenges", "key": "get_adhoc_challenges"}, "4": { "desc": "Get available badge challenges", "key": "get_available_badge_challenges", }, "5": {"desc": "Get active goals", "key": "get_active_goals"}, "6": {"desc": "Get future goals", "key": "get_future_goals"}, "7": {"desc": "Get past goals", "key": "get_past_goals"}, "8": {"desc": "Get badge challenges", "key": "get_badge_challenges"}, "9": { "desc": "Get non-completed badge challenges", "key": "get_non_completed_badge_challenges", }, "0": { "desc": "Get virtual challenges in progress", "key": "get_inprogress_virtual_challenges", }, "a": {"desc": "Get race predictions", "key": "get_race_predictions"}, "b": { "desc": "Get hill score from '{week_start}' to '{today}'", "key": "get_hill_score", }, "c": { "desc": "Get endurance score from '{week_start}' to '{today}'", "key": "get_endurance_score", }, "d": {"desc": "Get available badges", "key": "get_available_badges"}, "e": {"desc": "Get badges in progress", "key": "get_in_progress_badges"}, "f": {"desc": "Effective daily goals", "key": "get_effective_goals"}, "g": {"desc": "User goals", "key": "get_user_goals"}, "h": {"desc": "Badge attributes", "key": "get_badge_attributes"}, "i": {"desc": "Latest earned badges", "key": "get_latest_earned_badges"}, "j": { "desc": "Available virtual challenges", "key": "get_available_virtual_challenges", }, "k": { "desc": "Personal record candidates", "key": "get_personal_record_candidates", }, "l": {"desc": "Personal record types", "key": "get_personal_record_types"}, "m": { "desc": "Set or reset the step goal (interactive)", "key": "set_steps_goal", }, "n": { "desc": "Set a daily goal: intensity minutes, floors, hydration (interactive)", "key": "set_daily_goal", }, }, }, "8": { "name": "⌚ Device & Technical", "options": { "1": {"desc": "Get all device information", "key": "get_devices"}, "2": {"desc": "Get device alarms", "key": "get_device_alarms"}, "3": {"desc": "Get solar data from your devices", "key": "get_solar_data"}, "4": { "desc": "Request data reload (epoch) for '{today}'", "key": "request_reload", }, "5": {"desc": "Get device settings", "key": "get_device_settings"}, "6": {"desc": "Get device last used", "key": "get_device_last_used"}, "7": { "desc": "Get primary training device", "key": "get_primary_training_device", }, "8": {"desc": "All devices (incl. inactive)", "key": "get_all_devices"}, "9": {"desc": "Historical devices", "key": "get_historical_devices"}, "0": {"desc": "Active devices", "key": "get_active_devices"}, "a": {"desc": "Paired sensors", "key": "get_sensors"}, "b": {"desc": "Device message queue", "key": "get_device_messages"}, "c": { "desc": "Set primary training device (interactive)", "key": "set_primary_training_device", }, }, }, "9": { "name": "šŸŽ½ Gear & Equipment", "options": { "1": {"desc": "Get user gear list", "key": "get_gear"}, "2": {"desc": "Get gear defaults", "key": "get_gear_defaults"}, "3": {"desc": "Get gear statistics", "key": "get_gear_stats"}, "4": {"desc": "Get gear activities", "key": "get_gear_activities"}, "5": {"desc": "Set gear default", "key": "set_gear_default"}, "6": { "desc": "Track gear usage (total time used)", "key": "track_gear_usage", }, "7": { "desc": "Add and remove gear to/from activity (interactive)", "key": "add_and_remove_gear_to_activity", }, "8": { "desc": "Create new gear, e.g. shoes (interactive)", "key": "create_gear", }, "9": {"desc": "Gear list (v2)", "key": "get_gear_list"}, "0": {"desc": "Gear types", "key": "get_gear_types"}, "a": { "desc": "Gear on latest activity (v2)", "key": "get_activity_gear_v2", }, "b": { "desc": "Update gear notes (interactive)", "key": "update_gear_notes", }, "c": { "desc": "Delete gear (interactive, confirms by name)", "key": "delete_gear", }, }, }, "0": { "name": "šŸ’§ Hydration & Wellness", "options": { "1": { "desc": "Get hydration data for '{today}'", "key": "get_hydration_data", }, "2": {"desc": "Add hydration data", "key": "add_hydration_data"}, "3": { "desc": "Set blood pressure and pulse (interactive)", "key": "set_blood_pressure", }, "4": {"desc": "Get pregnancy summary data", "key": "get_pregnancy_summary"}, "5": { "desc": "Get all day events for '{week_start}'", "key": "get_all_day_events", }, "6": { "desc": "Get body battery events for '{week_start}'", "key": "get_body_battery_events", }, "7": { "desc": "Get menstrual data for '{today}'", "key": "get_menstrual_data_for_date", }, "8": { "desc": "Get menstrual calendar from '{week_start}' to '{today}'", "key": "get_menstrual_calendar_data", }, "9": { "desc": "Delete blood pressure entry", "key": "delete_blood_pressure", }, "a": { "desc": "Get nutrition daily food log for '{today}'", "key": "get_nutrition_daily_food_log", }, "b": { "desc": "Get nutrition daily meals for '{today}'", "key": "get_nutrition_daily_meals", }, "c": { "desc": "Get nutrition daily settings for '{today}'", "key": "get_nutrition_daily_settings", }, "d": { "desc": "Get last confirmed menstrual cycle for '{today}'", "key": "get_menstrual_last_confirmed", }, "e": { "desc": "Get menstrual cycle summary for '{today}'", "key": "get_menstrual_cycle_summary", }, "f": { "desc": "Get menstrual reports (6 cycles) ending '{today}'", "key": "get_menstrual_reports", }, "g": { "desc": "Update menstrual daily log (interactive)", "key": "update_menstrual_daily_log", }, "h": { "desc": "Update menstrual calendar (interactive)", "key": "update_menstrual_calendar", }, "i": { "desc": "Initialize menstrual cycle setup (interactive)", "key": "init_menstrual_cycle_setup", }, "j": { "desc": "Confirm menstrual period start (interactive)", "key": "confirm_menstrual_period_start", }, "k": { "desc": "Update menstrual tracking settings (interactive)", "key": "update_menstrual_settings", }, "l": {"desc": "Get jet lag trips", "key": "get_jetlag_trips"}, "m": { "desc": "Add jet lag trip (interactive)", "key": "add_jetlag_trip", }, "n": { "desc": "Update jet lag trip (interactive)", "key": "update_jetlag_trip", }, "o": { "desc": "Delete jet lag trip (interactive)", "key": "delete_jetlag_trip", }, "0": {"desc": "Nutrition status", "key": "get_nutrition_status"}, "p": { "desc": "Calorie summary per meal, last 7 days", "key": "get_calorie_summary", }, "r": { "desc": "ECG recordings per day, last 30 days", "key": "get_ecg_daily", }, "s": {"desc": "ECG recordings list", "key": "get_ecg_list"}, "t": {"desc": "Jet lag status for today", "key": "get_jetlag_status"}, "u": { "desc": "Edit the note of a blood pressure reading (interactive)", "key": "update_blood_pressure", }, }, }, "a": { "name": "šŸ”§ System & Export", "options": { "1": {"desc": "Create sample health report", "key": "create_health_report"}, "2": { "desc": "Remove stored login tokens (logout)", "key": "remove_tokens", }, "3": {"desc": "Disconnect from Garmin Connect", "key": "disconnect"}, "4": {"desc": "Execute GraphQL query", "key": "query_garmin_graphql"}, "5": { "desc": "Download Health Snapshot ZIP for today", "key": "download_health_snapshot", }, }, }, "b": { "name": "šŸ“… Training Plans & Calendar", "options": { "1": {"desc": "Get training plans", "key": "get_training_plans"}, "2": {"desc": "Get training plan by ID", "key": "get_training_plan_by_id"}, "3": { "desc": "Upload typed strength workout (sample)", "key": "upload_strength_workout", }, "4": { "desc": "Search exercise catalog", "key": "search_exercise_catalog", }, "5": { "desc": "Update workout in place (edit existing template)", "key": "update_workout", }, "6": { "desc": "Push a workout to a device (interactive)", "key": "push_workout_to_device", }, "7": { "desc": "Get scheduled workout by ID", "key": "get_scheduled_workout_by_id", }, "8": { "desc": "Delete a workout template (interactive)", "key": "delete_workout", }, "9": { "desc": "Unschedule a scheduled workout", "key": "unschedule_workout", }, "0": { "desc": "Upload timed strength workout with step notes (sample)", "key": "upload_timed_strength_workout", }, "a": { "desc": "Scheduled workouts, next 60 days (incl. adaptive plans)", "key": "get_scheduled_workouts_by_period", }, "b": {"desc": "Workout counts per sport", "key": "get_workout_count"}, "c": {"desc": "Workout sport types", "key": "get_workout_sport_types"}, "d": {"desc": "Workout type dictionaries", "key": "get_workout_types"}, "e": { "desc": "Strength benchmark exercises", "key": "get_strength_benchmarks", }, "f": {"desc": "Active training plans", "key": "get_active_training_plans"}, "g": { "desc": "Search Garmin training plan catalogue", "key": "search_training_plans", }, "h": {"desc": "Calendar year overview", "key": "get_calendar_year"}, "i": { "desc": "Calendar week (items of this week)", "key": "get_calendar_week", }, "j": {"desc": "Calendar events this year", "key": "get_calendar_events"}, "k": {"desc": "Upcoming events", "key": "get_upcoming_events"}, "l": {"desc": "Primary race event", "key": "get_primary_event"}, "m": { "desc": "Add a calendar note for today (interactive)", "key": "calendar_note", }, }, }, "c": { "name": "⛳ Golf", "options": { "1": {"desc": "Get golf scorecard summary", "key": "get_golf_summary"}, "2": {"desc": "Get golf scorecard by ID", "key": "get_golf_scorecard"}, "3": { "desc": "Get golf shot data by scorecard ID", "key": "get_golf_shot_data", }, "4": {"desc": "Get golf club stats", "key": "get_golf_club_stats"}, "5": {"desc": "Get golf user stats", "key": "get_golf_user_stats"}, }, }, "d": { "name": "āœļø Activity Editing", "options": { "1": { "desc": "Set activity description (latest activity)", "key": "set_activity_description", }, "2": { "desc": "Set activity exercise sets (strength activity)", "key": "set_activity_exercise_sets", }, "3": { "desc": "Rename latest activity via update_activity (interactive)", "key": "update_activity", }, }, }, "e": { "name": "šŸƒ Activity Details & Courses", "options": { "1": { "desc": "Search activities (walking, last 7 days)", "key": "search_activities", }, "2": { "desc": "Fastest running splits this year", "key": "get_fastest_splits", }, "3": {"desc": "Favorite activities", "key": "get_favorite_activities"}, "4": {"desc": "Laps of latest activity", "key": "get_activity_laps"}, "5": { "desc": "Map details of latest activity", "key": "get_activity_map_details", }, "6": { "desc": "Previous/next of latest activity", "key": "get_adjacent_activities", }, "7": {"desc": "Activity event types", "key": "get_activity_event_types"}, "8": { "desc": "Segments in latest activity", "key": "get_activity_segments", }, "9": { "desc": "Personal records set by latest activity", "key": "get_personal_records_for_activity", }, "0": {"desc": "My courses", "key": "get_courses"}, "a": {"desc": "Favorite courses", "key": "get_course_favorites"}, "b": {"desc": "PacePro pace bands", "key": "get_pace_bands"}, "c": { "desc": "Convert latest activity to a course (not saved)", "key": "convert_activity_to_course", }, }, }, } current_category = None # --- Helpers for the web-app endpoint categories (see docs/API_ENDPOINTS.md) -- def _today() -> str: return config.today.isoformat() def _week_ago() -> str: return config.week_start.isoformat() def _month_ago() -> str: return config.month_start.isoformat() def _latest_activity_id(api: Garmin) -> int: """Return the id of the most recent activity (raises when there is none).""" activity = api.get_last_activity() if not activity: raise ValueError("No activities found on this account") return int(activity["activityId"]) def _web(api: Garmin, method: str, args_fn=None, kwargs_fn=None): """Build a menu action that calls ``api.`` with lazily built arguments. Arguments are computed when the option runs, so dates follow ``config.today`` and activity ids are looked up on demand. """ def run(): args = tuple(args_fn()) if args_fn else () kwargs = dict(kwargs_fn()) if kwargs_fn else {} shown = ", ".join( [repr(a) for a in args] + [f"{k}={v!r}" for k, v in kwargs.items()] ) call_and_display( getattr(api, method), *args, method_name=method, api_call_desc=f"api.{method}({shown})", **kwargs, ) return run def _menu_label(desc: str) -> str: """Fill a menu label's date placeholders with the dates as of now. Labels are defined once at import, so they hold ``{today}`` / ``{week_start}`` / ``{month_start}`` and are filled in when the menu is printed; a session left open past midnight then shows the new dates. """ return ( desc.replace("{today}", config.today.isoformat()) .replace("{week_start}", config.week_start.isoformat()) .replace("{month_start}", config.month_start.isoformat()) ) def print_main_menu(): """Print the main category menu.""" print("\n" + "=" * 50) print("🚓 Full-blown Garmin Connect API Demo - Main Menu") print("=" * 50) print("Select a category:") print() for key, category in menu_categories.items(): print(f" [{key}] {category['name']}") print() print(" [q] Exit program") print() print("Make your selection: ", end="", flush=True) def print_category_menu(category_key: str): """Print options for a specific category.""" if category_key not in menu_categories: return False category = menu_categories[category_key] print(f"\nšŸ“‹ #{category_key} {category['name']} - Options") print("-" * 40) for key, option in category["options"].items(): print(f" [{key}] {_menu_label(option['desc'])}") print() print(" [q] Back to main menu") print() print("Make your selection: ", end="", flush=True) return True def get_mfa() -> str: """Get MFA token.""" return input("MFA one-time code: ") class DataExporter: """Utilities for exporting data in various formats.""" @staticmethod def save_json(data: Any, filename: str, pretty: bool = True) -> str: """Save data as JSON file.""" filepath = config.export_dir / f"{_safe_filename_component(filename)}.json" with _open_private(filepath, "w", encoding="utf-8") as f: if pretty: json.dump(data, f, indent=4, default=str, ensure_ascii=False) else: json.dump(data, f, default=str, ensure_ascii=False) return str(filepath) @staticmethod def create_health_report(api_instance: Garmin) -> str: """Create a comprehensive health report in JSON and HTML formats.""" report_data = { "generated_at": datetime.datetime.now().isoformat(), "user_info": {"full_name": "N/A", "unit_system": "N/A"}, "today_summary": {}, "recent_activities": [], "health_metrics": {}, "weekly_data": [], "device_info": [], } try: # Basic user info report_data["user_info"]["full_name"] = ( api_instance.get_full_name() or "N/A" ) report_data["user_info"]["unit_system"] = ( api_instance.get_unit_system() or "N/A" ) # Today's summary today_str = config.today.isoformat() report_data["today_summary"] = api_instance.get_user_summary(today_str) # Recent activities recent_activities = api_instance.get_activities(0, 10) report_data["recent_activities"] = recent_activities or [] # Weekly data for trends for i in range(7): date = config.today - datetime.timedelta(days=i) try: daily_data = api_instance.get_user_summary(date.isoformat()) if daily_data: daily_data["date"] = date.isoformat() report_data["weekly_data"].append(daily_data) except Exception as e: print( f"Skipping data for {date.isoformat()}: {e}" ) # Skip if data not available # Health metrics for today health_metrics = {} metrics_to_fetch = [ ("heart_rate", lambda: api_instance.get_heart_rates(today_str)), # The Step Goal card reads totalSteps and dailyStepGoal, which are in the # daily user summary; get_steps_data returns a list of 15 minute intervals. ("steps", lambda: api_instance.get_user_summary(today_str)), ("sleep", lambda: api_instance.get_sleep_data(today_str)), ("stress", lambda: api_instance.get_all_day_stress(today_str)), ( "body_battery", lambda: api_instance.get_body_battery( config.week_start.isoformat(), today_str ), ), ] for metric_name, fetch_func in metrics_to_fetch: try: health_metrics[metric_name] = fetch_func() except Exception: health_metrics[metric_name] = None report_data["health_metrics"] = health_metrics # Device information try: report_data["device_info"] = api_instance.get_devices() except Exception: report_data["device_info"] = [] except Exception as e: print(f"Error creating health report: {e}") # Create HTML version html_filepath = DataExporter.create_readable_health_report(report_data) print(f"šŸ“Š Report created: {html_filepath}") return html_filepath @staticmethod def create_readable_health_report(report_data: dict) -> str: """Create a readable HTML report from comprehensive health data.""" timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S") html_filename = f"health_report_{timestamp}.html" # Extract key information user_name = report_data.get("user_info", {}).get("full_name", "Unknown User") generated_at = report_data.get("generated_at", "Unknown") # Create HTML content with complete styling html_content = f""" Garmin Health Report - {_html(user_name)}

šŸƒ Garmin Health Report

{_html(user_name)}

Generated: {_html(generated_at)}

Date: {_html(config.today.isoformat())}

""" # Today's Summary Section today_summary = report_data.get("today_summary", {}) if today_summary: steps = today_summary.get("totalSteps", 0) calories = today_summary.get("totalKilocalories", 0) distance = ( round(today_summary.get("totalDistanceMeters", 0) / 1000, 2) if today_summary.get("totalDistanceMeters") else 0 ) active_calories = today_summary.get("activeKilocalories", 0) html_content += f"""

šŸ“ˆ Today's Activity Summary

šŸ‘Ÿ Steps

{_html(f"{steps:,}")} steps

šŸ”„ Calories

{_html(f"{calories:,}")} total
{_html(f"{active_calories:,}")} active

šŸ“ Distance

{_html(distance)} km
""" else: html_content += """

šŸ“ˆ Today's Activity Summary

No activity data available for today
""" # Health Metrics Section health_metrics = report_data.get("health_metrics", {}) if health_metrics and any(health_metrics.values()): html_content += """

ā¤ļø Health Metrics

""" # Heart Rate heart_rate = health_metrics.get("heart_rate", {}) if heart_rate and isinstance(heart_rate, dict): resting_hr = heart_rate.get("restingHeartRate", "N/A") max_hr = heart_rate.get("maxHeartRate", "N/A") html_content += f"""

šŸ’“ Heart Rate

{_html(resting_hr)} bpm (resting)
Max: {_html(max_hr)} bpm
""" # Sleep Data sleep_data = health_metrics.get("sleep", {}) if ( sleep_data and isinstance(sleep_data, dict) and "dailySleepDTO" in sleep_data ): sleep_seconds = sleep_data["dailySleepDTO"].get("sleepTimeSeconds", 0) sleep_hours = round(sleep_seconds / 3600, 1) if sleep_seconds else 0 deep_sleep = sleep_data["dailySleepDTO"].get("deepSleepSeconds", 0) deep_hours = round(deep_sleep / 3600, 1) if deep_sleep else 0 html_content += f"""

😓 Sleep

{_html(sleep_hours)} hours
Deep Sleep: {_html(deep_hours)} hours
""" # Steps steps_data = health_metrics.get("steps", {}) if steps_data and isinstance(steps_data, dict): total_steps = steps_data.get("totalSteps", 0) goal = steps_data.get("dailyStepGoal", 10000) html_content += f"""

šŸŽÆ Step Goal

{_html(f"{total_steps:,}")} of {_html(f"{goal:,}")}
Goal: {_html(round((total_steps / goal) * 100) if goal else 0)}%
""" # Stress Data stress_data = health_metrics.get("stress", {}) if stress_data and isinstance(stress_data, dict): avg_stress = stress_data.get("avgStressLevel", "N/A") max_stress = stress_data.get("maxStressLevel", "N/A") html_content += f"""

😰 Stress Level

{_html(avg_stress)} avg
Max: {_html(max_stress)}
""" # Body Battery body_battery = health_metrics.get("body_battery", []) if body_battery and isinstance(body_battery, list) and body_battery: latest_bb = body_battery[-1] if body_battery else {} charged = latest_bb.get("charged", "N/A") drained = latest_bb.get("drained", "N/A") html_content += f"""

šŸ”‹ Body Battery

+{_html(charged)} charged
-{_html(drained)} drained
""" html_content += "
\n
\n" else: html_content += """

ā¤ļø Health Metrics

No health metrics data available
""" # Weekly Trends Section weekly_data = report_data.get("weekly_data", []) if weekly_data: html_content += """

šŸ“Š Weekly Trends (Last 7 Days)

""" for daily in weekly_data[:7]: # Show last 7 days date = daily.get("date", "Unknown") steps = daily.get("totalSteps", 0) calories = daily.get("totalKilocalories", 0) distance = ( round(daily.get("totalDistanceMeters", 0) / 1000, 2) if daily.get("totalDistanceMeters") else 0 ) html_content += f"""

šŸ“… {_html(date)}

{_html(f"{steps:,}")} steps
{_html(f"{calories:,}")} kcal
{_html(distance)} km
""" html_content += "
\n
\n" # Recent Activities Section activities = report_data.get("recent_activities", []) if activities: html_content += """

šŸƒ Recent Activities

""" for activity in activities[:5]: # Show last 5 activities name = activity.get("activityName", "Unknown Activity") activity_type = activity.get("activityType", {}).get( "typeKey", "Unknown" ) date = ( activity.get("startTimeLocal", "").split("T")[0] if activity.get("startTimeLocal") else "Unknown" ) duration = activity.get("duration", 0) duration_min = round(duration / 60, 1) if duration else 0 distance = ( round(activity.get("distance", 0) / 1000, 2) if activity.get("distance") else 0 ) calories = activity.get("calories", 0) avg_hr = activity.get("avgHR", 0) html_content += f"""

{_html(name)} ({_html(activity_type)})

Date: {_html(date)}
Duration: {_html(duration_min)} min
Distance: {_html(distance)} km
Calories: {_html(calories)}
Avg HR: {_html(avg_hr)} bpm
""" html_content += "
\n" else: html_content += """

šŸƒ Recent Activities

No recent activities found
""" # Device Information device_info = report_data.get("device_info", []) if device_info: html_content += """

⌚ Device Information

""" for device in device_info: device_name = device.get("displayName", "Unknown Device") model = device.get("productDisplayName", "Unknown Model") version = device.get("softwareVersion", "Unknown") html_content += f"""

{_html(device_name)}

Model: {_html(model)}
Software: {_html(version)}
""" html_content += "
\n
\n" # Footer html_content += f"""
""" # Save HTML file html_filepath = config.export_dir / html_filename with _open_private(html_filepath, "w", encoding="utf-8") as f: f.write(html_content) return str(html_filepath) def safe_api_call(api_method, *args, method_name: str | None = None, **kwargs): """Centralized API call wrapper with comprehensive error handling. This function provides unified error handling for all Garmin Connect API calls. It handles common HTTP errors (400, 401, 403, 404, 429, 500, 503) with user-friendly messages and provides consistent error reporting. Usage: success, result, error_msg = safe_api_call(api.get_user_summary) Args: api_method: The API method to call *args: Positional arguments for the API method method_name: Human-readable name for the API method (optional) **kwargs: Keyword arguments for the API method Returns: tuple: (success: bool, result: Any, error_message: str|None) """ if method_name is None: method_name = getattr(api_method, "__name__", str(api_method)) t0 = time.perf_counter() try: result = api_method(*args, **kwargs) elapsed_ms = (time.perf_counter() - t0) * 1000 _LOGGER.debug("api.%s OK in %.1f ms", method_name, elapsed_ms) return True, result, None except GarminConnectNotFoundError as e: _LOGGER.debug( "api.%s FAIL in %.1f ms: %s", method_name, (time.perf_counter() - t0) * 1000, e, ) error_msg = ( "Endpoint not found (404) - This feature may have been moved or removed" ) print(f"āš ļø {method_name} failed: {error_msg}") return False, None, error_msg except GarminConnectConnectionError as e: _LOGGER.debug( "api.%s FAIL in %.1f ms: %s", method_name, (time.perf_counter() - t0) * 1000, e, ) # Handle specific HTTP errors more gracefully error_str = str(e) # Extract status code more reliably status_code = None if hasattr(e, "response") and hasattr(e.response, "status_code"): status_code = e.response.status_code # Handle specific status codes if status_code == 400 or ("400" in error_str and "Bad Request" in error_str): error_msg = "Endpoint not available (400 Bad Request) - This feature may not be enabled for your account or region" # Don't print for 400 errors as they're often expected for unavailable features elif status_code == 401 or "401" in error_str: error_msg = ( "Authentication required (401 Unauthorized) - Please re-authenticate" ) print(f"āš ļø {method_name} failed: {error_msg}") elif status_code == 403 or "403" in error_str: error_msg = "Access denied (403 Forbidden) - Your account may not have permission for this feature" print(f"āš ļø {method_name} failed: {error_msg}") elif status_code == 410 or "410" in error_str: error_msg = "Resource no longer available (410 Gone) - This data does not exist or the endpoint has been retired" print(f"āš ļø {method_name} failed: {error_msg}") elif status_code == 429 or "429" in error_str: error_msg = ( "Rate limit exceeded (429) - Please wait before making more requests" ) print(f"āš ļø {method_name} failed: {error_msg}") elif status_code == 500 or "500" in error_str: error_msg = "Server error (500) - Garmin's servers are experiencing issues" print(f"āš ļø {method_name} failed: {error_msg}") elif status_code == 503 or "503" in error_str: error_msg = "Service unavailable (503) - Garmin's servers are temporarily unavailable" print(f"āš ļø {method_name} failed: {error_msg}") else: error_msg = f"HTTP error: {e}" print(f"āš ļø {method_name} failed: {error_msg}") return False, None, error_msg except GarminConnectAuthenticationError as e: _LOGGER.debug( "api.%s FAIL in %.1f ms: %s", method_name, (time.perf_counter() - t0) * 1000, e, ) error_msg = f"Authentication issue: {e}" print(f"āš ļø {method_name} failed: {error_msg}") return False, None, error_msg except GarminConnectConnectionError as e: # noqa: B025 _LOGGER.debug( "api.%s FAIL in %.1f ms: %s", method_name, (time.perf_counter() - t0) * 1000, e, ) error_str = str(e) # Extract a clean message by detecting common HTTP status codes if "410" in error_str: error_msg = "Resource no longer available (410 Gone) - This data does not exist or the endpoint has been retired" elif "403" in error_str: error_msg = "Access denied (403 Forbidden) - Your account may not have permission for this feature" elif "404" in error_str: error_msg = ( "Endpoint not found (404) - This feature may have been moved or removed" ) else: error_msg = f"Connection issue: {e}" print(f"āš ļø {method_name} failed: {error_msg}") return False, None, error_msg except Exception as e: _LOGGER.debug( "api.%s FAIL in %.1f ms: %s", method_name, (time.perf_counter() - t0) * 1000, e, ) error_msg = f"Unexpected error: {e}" print(f"āš ļø {method_name} failed: {error_msg}") return False, None, error_msg def call_and_display( api_method=None, *args, method_name: str | None = None, api_call_desc: str | None = None, group_name: str | None = None, api_responses: list | None = None, **kwargs, ): """Unified wrapper that calls API methods safely and displays results. Can handle both single API calls and grouped API responses. For single API calls: call_and_display(api.get_user_summary, "2024-01-01") For grouped responses: call_and_display(group_name="User Data", api_responses=[("api.get_user", data)]) Args: api_method: The API method to call (for single calls) *args: Positional arguments for the API method method_name: Human-readable name for the API method (optional) api_call_desc: Description for display purposes (optional) group_name: Name for grouped display (when displaying multiple responses) api_responses: List of (api_call_desc, result) tuples for grouped display **kwargs: Keyword arguments for the API method Returns: For single calls: tuple: (success: bool, result: Any) For grouped calls: None """ # Handle grouped display mode if group_name is not None and api_responses is not None: return _display_group(group_name, api_responses) # Handle single API call mode if api_method is None: raise ValueError( "Either api_method or (group_name + api_responses) must be provided" ) if method_name is None: method_name = getattr(api_method, "__name__", str(api_method)) if api_call_desc is None: # Try to construct a reasonable description args_str = ", ".join(str(arg) for arg in args) kwargs_str = ", ".join(f"{k}={v}" for k, v in kwargs.items()) all_args = ", ".join(filter(None, [args_str, kwargs_str])) api_call_desc = f"{method_name}({all_args})" success, result, error_msg = safe_api_call( api_method, *args, method_name=method_name, **kwargs ) if success: _display_single(api_call_desc, result) return True, result # Display error in a consistent format _display_single(f"{api_call_desc} [ERROR]", {"error": error_msg}) return False, None def _display_single(api_call: str, output: Any): """Internal function to display single API response.""" print(f"\nšŸ“” API Call: {api_call}") print("-" * 50) if output is None: print("No data returned") # Save empty JSON to response.json in the export directory response_file = config.export_dir / "response.json" with _open_private(response_file, "w", encoding="utf-8") as f: f.write(f"{'-' * 20} {api_call} {'-' * 20}\n{{}}\n{'-' * 77}\n") return try: # Format the output if isinstance(output, int | str | dict | list): formatted_output = json.dumps(output, indent=2, default=str) else: formatted_output = str(output) # Save to response.json in the export directory response_content = ( f"{'-' * 20} {api_call} {'-' * 20}\n{formatted_output}\n{'-' * 77}\n" ) response_file = config.export_dir / "response.json" with _open_private(response_file, "w", encoding="utf-8") as f: f.write(response_content) print(formatted_output) print("-" * 77) except Exception as e: print(f"Error formatting output: {e}") print(output) def _display_group(group_name: str, api_responses: list[tuple[str, Any]]): """Internal function to display grouped API responses.""" print(f"\nšŸ“” API Group: {group_name}") # Collect all responses for saving all_responses = {} response_content_parts = [] for api_call, output in api_responses: print(f"\nšŸ“‹ {api_call}") print("-" * 50) if output is None: print("No data returned") formatted_output = "{}" else: try: if isinstance(output, int | str | dict | list): formatted_output = json.dumps(output, indent=2, default=str) else: formatted_output = str(output) print(formatted_output) except Exception as e: print(f"Error formatting output: {e}") formatted_output = str(output) print(output) # Store for grouped response file all_responses[api_call] = output response_content_parts.append( f"{'-' * 20} {api_call} {'-' * 20}\n{formatted_output}" ) print("-" * 50) # Save grouped responses to file try: response_file = config.export_dir / "response.json" header = "=" * 20 + f" {group_name} " + "=" * 20 footer = "=" * 77 content_lines = [header, *response_content_parts, footer, ""] grouped_content = "\n".join(content_lines) with _open_private(response_file, "w", encoding="utf-8") as f: f.write(grouped_content) print(f"\nāœ… Grouped responses saved to: {response_file}") print("=" * 77) except Exception as e: print(f"Error saving grouped responses: {e}") def format_timedelta(td): minutes, seconds = divmod(td.seconds + td.days * 86400, 60) hours, minutes = divmod(minutes, 60) return f"{hours:d}:{minutes:02d}:{seconds:02d}" def safe_call_for_group( api_method, *args, method_name: str | None = None, api_call_desc: str | None = None, **kwargs, ): """Safe API call wrapper that returns result suitable for grouped display. Args: api_method: The API method to call *args: Positional arguments for the API method method_name: Human-readable name for the API method (optional) api_call_desc: Description for display purposes (optional) **kwargs: Keyword arguments for the API method Returns: tuple: (api_call_description: str, result: Any) - suitable for grouped display """ if method_name is None: method_name = getattr(api_method, "__name__", str(api_method)) if api_call_desc is None: # Try to construct a reasonable description args_str = ", ".join(str(arg) for arg in args) kwargs_str = ", ".join(f"{k}={v}" for k, v in kwargs.items()) all_args = ", ".join(filter(None, [args_str, kwargs_str])) api_call_desc = f"{method_name}({all_args})" success, result, error_msg = safe_api_call( api_method, *args, method_name=method_name, **kwargs ) if success: return api_call_desc, result return f"{api_call_desc} [ERROR]", {"error": error_msg} def get_solar_data(api: Garmin) -> None: """Get solar data from all Garmin devices using centralized error handling.""" print("ā˜€ļø Getting solar data from devices...") # Collect all API responses for grouped display api_responses = [] # Get all devices using centralized wrapper api_responses.append( safe_call_for_group( api.get_devices, method_name="get_devices", api_call_desc="api.get_devices()", ) ) # Get device last used using centralized wrapper api_responses.append( safe_call_for_group( api.get_device_last_used, method_name="get_device_last_used", api_call_desc="api.get_device_last_used()", ) ) # Get the device list to process solar data devices_success, devices, _ = safe_api_call( api.get_devices, method_name="get_devices" ) # Get solar data for each device if devices_success and devices: for device in devices: device_id = device.get("deviceId") if device_id: device_name = device.get("displayName", f"Device {device_id}") print( f"\nā˜€ļø Getting solar data for device: {device_name} (ID: {device_id})" ) # Use centralized wrapper for each device's solar data api_responses.append( safe_call_for_group( api.get_device_solar_data, device_id, config.today.isoformat(), method_name="get_device_solar_data", api_call_desc=f"api.get_device_solar_data({device_id}, '{config.today.isoformat()}')", ) ) else: print("ā„¹ļø No devices found or error retrieving devices") # Display all responses as a group call_and_display(group_name="Solar Data Collection", api_responses=api_responses) def import_activity_file(api: Garmin) -> None: """Import activity data from file (not re-exported to Strava).""" import glob try: activity_files = glob.glob(config.activityfile) if not activity_files: print("āŒ No activity files found in test_data directory.") print("ā„¹ļø Please add FIT/GPX/TCX files to test_data before importing.") return print("Select a file to import (will NOT be re-exported to Strava):") for idx, fname in enumerate(activity_files, 1): print(f" {idx}. {fname}") while True: try: choice = int(input(f"Enter number (1-{len(activity_files)}): ")) if 1 <= choice <= len(activity_files): selected_file = activity_files[choice - 1] break print("Invalid selection. Try again.") except ValueError: print("Please enter a valid number.") print(f"šŸ“„ Importing activity from file: {selected_file}") call_and_display( api.import_activity, selected_file, method_name="import_activity", api_call_desc=f"api.import_activity({selected_file})", ) except FileNotFoundError: print(f"āŒ File not found: {selected_file}") except Exception as e: if "409" in str(e) or "duplicate" in str(e).lower(): print("āš ļø Activity already exists (duplicate)") else: print(f"āŒ Import failed: {e}") def upload_activity_file(api: Garmin) -> None: """Upload activity data from file.""" import glob try: # List all .gpx files in test_data gpx_files = glob.glob(config.activityfile) if not gpx_files: print("āŒ No .gpx files found in test_data directory.") print("ā„¹ļø Please add GPX files to test_data before uploading.") return print("Select a GPX file to upload:") for idx, fname in enumerate(gpx_files, 1): print(f" {idx}. {fname}") while True: try: choice = int(input(f"Enter number (1-{len(gpx_files)}): ")) if 1 <= choice <= len(gpx_files): selected_file = gpx_files[choice - 1] break print("Invalid selection. Try again.") except ValueError: print("Please enter a valid number.") print(f"šŸ“¤ Uploading activity from file: {selected_file}") call_and_display( api.upload_activity, selected_file, method_name="upload_activity", api_call_desc=f"api.upload_activity({selected_file})", ) except FileNotFoundError: print(f"āŒ File not found: {selected_file}") print("ā„¹ļø Please ensure the activity file exists in the current directory") except requests.exceptions.HTTPError as e: if e.response.status_code == 409: print( "āš ļø Activity already exists: This activity has already been uploaded to Garmin Connect" ) print("ā„¹ļø Garmin Connect prevents duplicate activities from being uploaded") print( "šŸ’” Try modifying the activity timestamps or creating a new activity file" ) elif e.response.status_code == 413: print( "āŒ File too large: The activity file exceeds Garmin Connect's size limit" ) print("šŸ’” Try compressing the file or reducing the number of data points") elif e.response.status_code == 422: print( "āŒ Invalid file format: The activity file format is not supported or corrupted" ) print("ā„¹ļø Supported formats: FIT, GPX, TCX") print("šŸ’” Try converting to a different format or check file integrity") elif e.response.status_code == 400: print("āŒ Bad request: Invalid activity data or malformed file") print( "šŸ’” Check if the activity file contains valid GPS coordinates and timestamps" ) elif e.response.status_code == 401: print("āŒ Authentication failed: Please login again") print("šŸ’” Your session may have expired") elif e.response.status_code == 429: print("āŒ Rate limit exceeded: Too many upload requests") print("šŸ’” Please wait a few minutes before trying again") else: print(f"āŒ HTTP Error {e.response.status_code}: {e}") except GarminConnectAuthenticationError as e: print(f"āŒ Authentication error: {e}") print("šŸ’” Please check your login credentials and try again") except GarminConnectConnectionError as e: print(f"āŒ Connection error: {e}") print("šŸ’” Please check your internet connection and try again") except GarminConnectTooManyRequestsError as e: print(f"āŒ Too many requests: {e}") print("šŸ’” Please wait a few minutes before trying again") except Exception as e: error_str = str(e) if "409 Client Error: Conflict" in error_str: print( "āš ļø Activity already exists: This activity has already been uploaded to Garmin Connect" ) print("ā„¹ļø Garmin Connect prevents duplicate activities from being uploaded") print( "šŸ’” Try modifying the activity timestamps or creating a new activity file" ) elif "413" in error_str and "Request Entity Too Large" in error_str: print( "āŒ File too large: The activity file exceeds Garmin Connect's size limit" ) print("šŸ’” Try compressing the file or reducing the number of data points") elif "422" in error_str and "Unprocessable Entity" in error_str: print( "āŒ Invalid file format: The activity file format is not supported or corrupted" ) print("ā„¹ļø Supported formats: FIT, GPX, TCX") print("šŸ’” Try converting to a different format or check file integrity") elif "400" in error_str and "Bad Request" in error_str: print("āŒ Bad request: Invalid activity data or malformed file") print( "šŸ’” Check if the activity file contains valid GPS coordinates and timestamps" ) elif "401" in error_str and "Unauthorized" in error_str: print("āŒ Authentication failed: Please login again") print("šŸ’” Your session may have expired") elif "429" in error_str and "Too Many Requests" in error_str: print("āŒ Rate limit exceeded: Too many upload requests") print("šŸ’” Please wait a few minutes before trying again") else: print(f"āŒ Unexpected error uploading activity: {e}") print("šŸ’” Please check the file format and try again") def download_activities_by_date(api: Garmin) -> None: """Download activities by date range in multiple formats.""" try: print( f"šŸ“„ Downloading activities by date range ({config.week_start.isoformat()} to {config.today.isoformat()})..." ) # Get activities for the date range (last 7 days as default) activities = api.get_activities_by_date( config.week_start.isoformat(), config.today.isoformat() ) if not activities: print("ā„¹ļø No activities found in the specified date range") return print(f"šŸ“Š Found {len(activities)} activities to download") # Download each activity in multiple formats for activity in activities: activity_id = activity.get("activityId") activity_name = activity.get("activityName", "Unknown") start_time = activity.get("startTimeLocal", "").replace(":", "-") if not activity_id: continue print(f"šŸ“„ Downloading: {activity_name} (ID: {activity_id})") # Download formats: GPX, TCX, ORIGINAL, CSV formats = ["GPX", "TCX", "ORIGINAL", "CSV"] for fmt in formats: try: safe_start = _safe_filename_component(start_time) safe_activity_id = _safe_filename_component(activity_id) filename = f"{safe_start}_{safe_activity_id}_ACTIVITY.{fmt.lower()}" if fmt == "ORIGINAL": filename = f"{safe_start}_{safe_activity_id}_ACTIVITY.zip" filepath = config.export_dir / filename if fmt == "CSV": # Get activity details for CSV export activity_details = api.get_activity_details(activity_id) with _open_private(filepath, "w", encoding="utf-8") as f: import json json.dump(activity_details, f, indent=2, ensure_ascii=False) print(f" āœ… {fmt}: {filename}") else: # Download the file from Garmin using proper enum values format_mapping = { "GPX": api.ActivityDownloadFormat.GPX, "TCX": api.ActivityDownloadFormat.TCX, "ORIGINAL": api.ActivityDownloadFormat.ORIGINAL, } dl_fmt = format_mapping[fmt] content = api.download_activity(activity_id, dl_fmt=dl_fmt) if content: with _open_private(filepath, "wb") as f: f.write(content) print(f" āœ… {fmt}: {filename}") else: print(f" āŒ {fmt}: No content available") except Exception as e: print(f" āŒ {fmt}: Error downloading - {e}") print(f"āœ… Activity downloads completed! Files saved to: {config.export_dir}") except Exception as e: print(f"āŒ Error downloading activities: {e}") def add_weigh_in_data(api: Garmin) -> None: """Add a weigh-in with timestamps.""" try: # Get weight input from user print("āš–ļø Adding weigh-in entry") print("-" * 30) # Weight input with validation while True: try: weight_str = input("Enter weight (30-300, default: 85.1): ").strip() if not weight_str: weight = 85.1 break weight = float(weight_str) if 30 <= weight <= 300: break print("āŒ Weight must be between 30 and 300") except ValueError: print("āŒ Please enter a valid number") # Unit selection while True: unit_input = input("Enter unit (kg/lbs, default: kg): ").strip().lower() if not unit_input: weight_unit = "kg" break if unit_input in ["kg", "lbs"]: weight_unit = unit_input break print("āŒ Please enter 'kg' or 'lbs'") print(f"āš–ļø Adding weigh-in: {weight} {weight_unit}") # Collect all API responses for grouped display api_responses = [] # Add a simple weigh-in result1 = api.add_weigh_in(weight=weight, unitKey=weight_unit) api_responses.append( (f"api.add_weigh_in(weight={weight}, unitKey={weight_unit})", result1) ) # Add a weigh-in with timestamps for yesterday import datetime yesterday = config.today - datetime.timedelta(days=1) # Get yesterday's date weigh_in_date = datetime.datetime.strptime(yesterday.isoformat(), "%Y-%m-%d") local_timestamp = weigh_in_date.strftime("%Y-%m-%dT%H:%M:%S") gmt_timestamp = weigh_in_date.astimezone(datetime.UTC).strftime( "%Y-%m-%dT%H:%M:%S" ) result2 = api.add_weigh_in_with_timestamps( weight=weight, unitKey=weight_unit, dateTimestamp=local_timestamp, gmtTimestamp=gmt_timestamp, ) api_responses.append( ( f"api.add_weigh_in_with_timestamps(weight={weight}, unitKey={weight_unit}, dateTimestamp={local_timestamp}, gmtTimestamp={gmt_timestamp})", result2, ) ) # Display all responses as a group call_and_display(group_name="Weigh-in Data Entry", api_responses=api_responses) print("āœ… Weigh-in data added successfully!") except Exception as e: print(f"āŒ Error adding weigh-in: {e}") # Helper functions for the new API methods def get_lactate_threshold_data(api: Garmin) -> None: """Get lactate threshold data.""" try: # Collect all API responses for grouped display api_responses = [] # Get latest lactate threshold latest = api.get_lactate_threshold(latest=True) api_responses.append(("api.get_lactate_threshold(latest=True)", latest)) # Get historical lactate threshold for past four weeks four_weeks_ago = config.today - datetime.timedelta(days=28) historical = api.get_lactate_threshold( latest=False, start_date=four_weeks_ago.isoformat(), end_date=config.today.isoformat(), aggregation="daily", ) api_responses.append( ( f"api.get_lactate_threshold(latest=False, start_date='{four_weeks_ago.isoformat()}', end_date='{config.today.isoformat()}', aggregation='daily')", historical, ) ) # Display all responses as a group call_and_display( group_name="Lactate Threshold Data", api_responses=api_responses ) except Exception as e: print(f"āŒ Error getting lactate threshold data: {e}") def get_activity_splits_data(api: Garmin) -> None: """Get activity splits for the last activity.""" try: activities = api.get_activities(0, 1) if activities: activity_id = activities[0]["activityId"] call_and_display( api.get_activity_splits, activity_id, method_name="get_activity_splits", api_call_desc=f"api.get_activity_splits({activity_id})", ) else: print("ā„¹ļø No activities found") except Exception as e: print(f"āŒ Error getting activity splits: {e}") def get_activity_typed_splits_data(api: Garmin) -> None: """Get activity typed splits for the last activity.""" try: activities = api.get_activities(0, 1) if activities: activity_id = activities[0]["activityId"] call_and_display( api.get_activity_typed_splits, activity_id, method_name="get_activity_typed_splits", api_call_desc=f"api.get_activity_typed_splits({activity_id})", ) else: print("ā„¹ļø No activities found") except Exception as e: print(f"āŒ Error getting activity typed splits: {e}") def get_activity_split_summaries_data(api: Garmin) -> None: """Get activity split summaries for the last activity.""" try: activities = api.get_activities(0, 1) if activities: activity_id = activities[0]["activityId"] call_and_display( api.get_activity_split_summaries, activity_id, method_name="get_activity_split_summaries", api_call_desc=f"api.get_activity_split_summaries({activity_id})", ) else: print("ā„¹ļø No activities found") except Exception as e: print(f"āŒ Error getting activity split summaries: {e}") def get_activity_weather_data(api: Garmin) -> None: """Get activity weather data for the last activity.""" try: activities = api.get_activities(0, 1) if activities: activity_id = activities[0]["activityId"] call_and_display( api.get_activity_weather, activity_id, method_name="get_activity_weather", api_call_desc=f"api.get_activity_weather({activity_id})", ) else: print("ā„¹ļø No activities found") except Exception as e: print(f"āŒ Error getting activity weather: {e}") def get_activity_hr_timezones_data(api: Garmin) -> None: """Get activity heart rate timezones for the last activity.""" try: activities = api.get_activities(0, 1) if activities: activity_id = activities[0]["activityId"] call_and_display( api.get_activity_hr_in_timezones, activity_id, method_name="get_activity_hr_in_timezones", api_call_desc=f"api.get_activity_hr_in_timezones({activity_id})", ) else: print("ā„¹ļø No activities found") except Exception as e: print(f"āŒ Error getting activity HR timezones: {e}") def get_activity_power_timezones_data(api: Garmin) -> None: """Get activity power timezones for the last activity.""" try: activities = api.get_activities(0, 1) if activities: activity_id = activities[0]["activityId"] call_and_display( api.get_activity_power_in_timezones, activity_id, method_name="get_activity_power_in_timezones", api_call_desc=f"api.get_activity_power_in_timezones({activity_id})", ) else: print("ā„¹ļø No activities found") except Exception as e: print(f"āŒ Error getting activity power timezones: {e}") def get_cycling_ftp_data(api: Garmin) -> None: """Get cycling Functional Threshold Power (FTP) information.""" call_and_display( api.get_cycling_ftp, method_name="get_cycling_ftp", api_call_desc="api.get_cycling_ftp()", ) def get_functional_threshold_power_range_data(api: Garmin) -> None: """Get historic functional threshold power (FTP) range.""" call_and_display( api.get_functional_threshold_power_range, config.week_start.isoformat(), config.today.isoformat(), sport="CYCLING", aggregation="daily", method_name="get_functional_threshold_power_range", api_call_desc=f"api.get_functional_threshold_power_range('{config.week_start.isoformat()}', '{config.today.isoformat()}', sport='CYCLING', aggregation='daily')", ) def get_activity_details_data(api: Garmin) -> None: """Get detailed activity information for the last activity, plus its per-sample metrics resolved from positional indices to metric names. """ try: activities = api.get_activities(0, 1) if activities: activity_id = activities[0]["activityId"] success, details = call_and_display( api.get_activity_details, activity_id, method_name="get_activity_details", api_call_desc=f"api.get_activity_details({activity_id})", ) if success: call_and_display( parse_activity_detail_metrics, details, method_name="parse_activity_detail_metrics", api_call_desc=( f"parse_activity_detail_metrics(details) for activity {activity_id}" ), ) else: print("ā„¹ļø No activities found") except Exception as e: print(f"āŒ Error getting activity details: {e}") def get_activity_gear_data(api: Garmin) -> None: """Get activity gear information for the last activity.""" try: activities = api.get_activities(0, 1) if activities: activity_id = activities[0]["activityId"] call_and_display( api.get_activity_gear, activity_id, method_name="get_activity_gear", api_call_desc=f"api.get_activity_gear({activity_id})", ) else: print("ā„¹ļø No activities found") except Exception as e: print(f"āŒ Error getting activity gear: {e}") def get_single_activity_data(api: Garmin) -> None: """Get single activity data for the last activity.""" try: activities = api.get_activities(0, 1) if activities: activity_id = activities[0]["activityId"] call_and_display( api.get_activity, activity_id, method_name="get_activity", api_call_desc=f"api.get_activity({activity_id})", ) else: print("ā„¹ļø No activities found") except Exception as e: print(f"āŒ Error getting single activity: {e}") def get_activity_images_data(api: Garmin) -> None: """Get photos attached to an activity (defaults to the most recent one).""" try: # The latest activity is only a convenience default; if looking it # up fails, still let the user type an ID they know has photos. default_id = "" try: last = api.get_last_activity() default_id = str(last["activityId"]) if last else "" except Exception as e: print(f"āš ļø Could not look up the most recent activity: {e}") prompt = f"Activity ID [{default_id}]: " if default_id else "Activity ID: " activity_id = input(prompt).strip() or default_id if not activity_id: print("ā„¹ļø No activity ID given") return success, images = call_and_display( api.get_activity_images, activity_id, method_name="get_activity_images", api_call_desc=f"api.get_activity_images({activity_id})", ) if success and not images: print("ā„¹ļø No photos attached to this activity") elif success: print("ā„¹ļø Photo URLs are presigned and expire after 24 hours") except Exception as e: print(f"āŒ Error getting activity images: {e}") def get_activity_exercise_sets_data(api: Garmin) -> None: """Get exercise sets for strength training activities.""" try: activities = api.get_activities( 0, 1, activitytype="fitness_equipment", activitysubtype="strength_training" ) activity_list = ( activities.get("activityList", []) if isinstance(activities, dict) else activities ) strength_activity = activity_list[0] if activity_list else None if strength_activity: activity_id = strength_activity["activityId"] call_and_display( api.get_activity_exercise_sets, activity_id, method_name="get_activity_exercise_sets", api_call_desc=f"api.get_activity_exercise_sets({activity_id})", ) else: # Return empty JSON response print("ā„¹ļø No strength training activities found") except Exception: print("ā„¹ļø No activity exercise sets available") def get_golf_scorecard_data(api: Garmin) -> None: """Get golf scorecard detail by ID.""" try: # First get summary to find valid IDs summary = api.get_golf_summary(limit=20) if not summary: print("āŒ No golf scorecards found") return scorecards = ( summary if isinstance(summary, list) else summary.get("scorecardList", summary.get("items", [summary])) ) if isinstance(scorecards, list) and scorecards: print("\n⛳ Recent golf scorecards:") for i, sc in enumerate(scorecards[:10], 1): sc_id = sc.get("scorecardId", sc.get("id", "?")) course = sc.get("courseName", sc.get("golfCourseName", "Unknown")) sc_date = sc.get("startTime", sc.get("date", "?")) print(f" [{i}] ID={sc_id} - {course} ({sc_date})") scorecard_id = input("\nEnter scorecard ID: ").strip() if not scorecard_id: print("āŒ No scorecard ID provided") return call_and_display( api.get_golf_scorecard, int(scorecard_id), method_name="get_golf_scorecard", api_call_desc=f"api.get_golf_scorecard({scorecard_id})", ) except Exception as e: print(f"āŒ Error getting golf scorecard: {e}") def get_golf_shot_data_entry(api: Garmin) -> None: """Get golf shot data by scorecard ID.""" try: # First get summary to find valid IDs summary = api.get_golf_summary(limit=20) if not summary: print("āŒ No golf scorecards found") return scorecards = ( summary if isinstance(summary, list) else summary.get("scorecardList", summary.get("items", [summary])) ) if isinstance(scorecards, list) and scorecards: print("\n⛳ Recent golf scorecards:") for i, sc in enumerate(scorecards[:10], 1): sc_id = sc.get("scorecardId", sc.get("id", "?")) course = sc.get("courseName", sc.get("golfCourseName", "Unknown")) print(f" [{i}] ID={sc_id} - {course}") scorecard_id = input("\nEnter scorecard ID: ").strip() if not scorecard_id: print("āŒ No scorecard ID provided") return holes = input( "Enter hole numbers 1-9, comma/dash separated " "(10-18 cannot be fetched with a filter; the API returns all 18 holes, or Enter for all): " ).strip() holes = holes or None call_and_display( api.get_golf_shot_data, int(scorecard_id), hole_numbers=holes, method_name="get_golf_shot_data", api_call_desc=f"api.get_golf_shot_data({scorecard_id}, hole_numbers={holes!r})", ) except Exception as e: print(f"āŒ Error getting golf shot data: {e}") def get_training_plan_by_id_data(api: Garmin) -> None: """Get training plan details by ID (routes FBT_ADAPTIVE plans to the adaptive endpoint).""" resp = api.get_training_plans() or {} training_plans = resp.get("trainingPlanList") or [] if not training_plans: print("ā„¹ļø No training plans found in your list") prompt_text = "Enter training plan ID: " else: prompt_text = "Enter training plan ID (press Enter for most recent): " user_input = input(prompt_text).strip() selected = None if user_input: try: wanted_id = int(user_input) selected = next( ( p for p in training_plans if int(p.get("trainingPlanId", 0)) == wanted_id ), None, ) if not selected: print( f"ā„¹ļø Plan ID {wanted_id} not found in your plans; attempting fetch anyway" ) plan_id = wanted_id plan_name = f"Plan {wanted_id}" plan_category = None else: plan_id = int(selected["trainingPlanId"]) plan_name = selected.get("name", str(plan_id)) plan_category = selected.get("trainingPlanCategory") except ValueError: print("āŒ Invalid plan ID") return else: if not training_plans: print("āŒ No training plans available and no ID provided") return selected = training_plans[-1] plan_id = int(selected["trainingPlanId"]) plan_name = selected.get("name", str(plan_id)) plan_category = selected.get("trainingPlanCategory") if plan_category == "FBT_ADAPTIVE": call_and_display( api.get_adaptive_training_plan_by_id, plan_id, method_name="get_adaptive_training_plan_by_id", api_call_desc=f"api.get_adaptive_training_plan_by_id({plan_id}) - {plan_name}", ) else: call_and_display( api.get_training_plan_by_id, plan_id, method_name="get_training_plan_by_id", api_call_desc=f"api.get_training_plan_by_id({plan_id}) - {plan_name}", ) def get_workout_by_id_data(api: Garmin) -> None: """Get workout by ID for the last workout.""" try: workouts = api.get_workouts() if workouts: workout_id = workouts[-1]["workoutId"] workout_name = workouts[-1]["workoutName"] call_and_display( api.get_workout_by_id, workout_id, method_name="get_workout_by_id", api_call_desc=f"api.get_workout_by_id({workout_id}) - {workout_name}", ) else: print("ā„¹ļø No workouts found") except Exception as e: print(f"āŒ Error getting workout by ID: {e}") def download_workout_data(api: Garmin) -> None: """Download workout to .FIT file.""" try: workouts = api.get_workouts() if workouts: workout_id = workouts[-1]["workoutId"] workout_name = workouts[-1]["workoutName"] print(f"šŸ“„ Downloading workout: {workout_name}") workout_data = api.download_workout(workout_id) if workout_data: safe_name = _safe_filename_component(workout_name) safe_id = _safe_filename_component(workout_id) output_file = config.export_dir / f"{safe_name}_{safe_id}.fit" with _open_private(output_file, "wb") as f: f.write(workout_data) print(f"āœ… Workout downloaded to: {output_file}") else: print("āŒ No workout data available") else: print("ā„¹ļø No workouts found") except Exception as e: print(f"āŒ Error downloading workout: {e}") def upload_workout_data(api: Garmin) -> None: """Upload workout from JSON file.""" try: print(f"šŸ“¤ Uploading workout from file: {config.workoutfile}") # Check if file exists if not os.path.exists(config.workoutfile): print(f"āŒ File not found: {config.workoutfile}") print( "ā„¹ļø Please ensure the workout JSON file exists in the test_data directory" ) return # Load the workout JSON data import json with open(config.workoutfile, encoding="utf-8") as f: workout_data = json.load(f) # Get current timestamp in Garmin format current_time = datetime.datetime.now() garmin_timestamp = current_time.strftime("%Y-%m-%dT%H:%M:%S.0") # Remove IDs that shouldn't be included when uploading a new workout fields_to_remove = ["workoutId", "ownerId", "updatedDate", "createdDate"] for field in fields_to_remove: if field in workout_data: del workout_data[field] # Add current timestamps workout_data["createdDate"] = garmin_timestamp workout_data["updatedDate"] = garmin_timestamp # Remove step IDs to ensure new ones are generated def clean_step_ids(workout_segments): """Recursively remove step IDs from workout structure.""" if isinstance(workout_segments, list): for segment in workout_segments: clean_step_ids(segment) elif isinstance(workout_segments, dict): # Remove stepId if present if "stepId" in workout_segments: del workout_segments["stepId"] # Recursively clean nested structures if "workoutSteps" in workout_segments: clean_step_ids(workout_segments["workoutSteps"]) # Handle any other nested lists or dicts for value in workout_segments.values(): if isinstance(value, list | dict): clean_step_ids(value) # Clean step IDs from workout segments if "workoutSegments" in workout_data: clean_step_ids(workout_data["workoutSegments"]) # Update workout name to indicate it's uploaded with current timestamp original_name = workout_data.get("workoutName", "Workout") workout_data["workoutName"] = ( f"Uploaded {original_name} - {current_time.strftime('%Y-%m-%d %H:%M:%S')}" ) print(f"šŸ“¤ Uploading workout: {workout_data['workoutName']}") # Upload the workout result = api.upload_workout(workout_data) if result: print("āœ… Workout uploaded successfully!") call_and_display( lambda: result, # Use a lambda to pass the result method_name="upload_workout", api_call_desc="api.upload_workout(workout_data)", ) else: print(f"āŒ Failed to upload workout from {config.workoutfile}") except FileNotFoundError: print(f"āŒ File not found: {config.workoutfile}") print("ā„¹ļø Please ensure the workout JSON file exists in the test_data directory") except json.JSONDecodeError as e: print(f"āŒ Invalid JSON format in {config.workoutfile}: {e}") print("ā„¹ļø Please check the JSON file format") except Exception as e: print(f"āŒ Error uploading workout: {e}") # Check for common upload errors error_str = str(e) if "400" in error_str: print("šŸ’” The workout data may be invalid or malformed") elif "401" in error_str: print("šŸ’” Authentication failed - please login again") elif "403" in error_str: print("šŸ’” Permission denied - check account permissions") elif "409" in error_str: print("šŸ’” Workout may already exist") elif "422" in error_str: print("šŸ’” Workout data validation failed") def upload_running_workout_data(api: Garmin) -> None: """Upload a typed running workout.""" try: import sys from pathlib import Path # Add test_data to path for imports test_data_path = Path(__file__).parent / "test_data" if str(test_data_path) not in sys.path: sys.path.insert(0, str(test_data_path)) from sample_running_workout import create_sample_running_workout print("šŸƒ Creating and uploading running workout...") workout = create_sample_running_workout() print(f"šŸ“¤ Uploading workout: {workout.workoutName}") result = api.upload_running_workout(workout) if result: print("āœ… Running workout uploaded successfully!") call_and_display( lambda: result, method_name="upload_running_workout", api_call_desc="api.upload_running_workout(workout)", ) else: print("āŒ Failed to upload running workout") except ImportError as e: print(f"āŒ Error: {e}") print( "šŸ’” Install pydantic with: pip install pydantic or pip install garminconnect[workout]" ) except Exception as e: print(f"āŒ Error uploading running workout: {e}") def upload_cycling_workout_data(api: Garmin) -> None: """Upload a typed cycling workout.""" try: import sys from pathlib import Path # Add test_data to path for imports test_data_path = Path(__file__).parent / "test_data" if str(test_data_path) not in sys.path: sys.path.insert(0, str(test_data_path)) from sample_cycling_workout import create_sample_cycling_workout print("🚓 Creating and uploading cycling workout...") workout = create_sample_cycling_workout() print(f"šŸ“¤ Uploading workout: {workout.workoutName}") result = api.upload_cycling_workout(workout) if result: print("āœ… Cycling workout uploaded successfully!") call_and_display( lambda: result, method_name="upload_cycling_workout", api_call_desc="api.upload_cycling_workout(workout)", ) else: print("āŒ Failed to upload cycling workout") except ImportError as e: print(f"āŒ Error: {e}") print( "šŸ’” Install pydantic with: pip install pydantic or pip install garminconnect[workout]" ) except Exception as e: print(f"āŒ Error uploading cycling workout: {e}") def upload_swimming_workout_data(api: Garmin) -> None: """Upload a typed swimming workout.""" try: import sys from pathlib import Path # Add test_data to path for imports test_data_path = Path(__file__).parent / "test_data" if str(test_data_path) not in sys.path: sys.path.insert(0, str(test_data_path)) from sample_swimming_workout import create_sample_swimming_workout print("šŸŠ Creating and uploading swimming workout...") workout = create_sample_swimming_workout() print(f"šŸ“¤ Uploading workout: {workout.workoutName}") result = api.upload_swimming_workout(workout) if result: print("āœ… Swimming workout uploaded successfully!") call_and_display( lambda: result, method_name="upload_swimming_workout", api_call_desc="api.upload_swimming_workout(workout)", ) else: print("āŒ Failed to upload swimming workout") except ImportError as e: print(f"āŒ Error: {e}") print( "šŸ’” Install pydantic with: pip install pydantic or pip install garminconnect[workout]" ) except Exception as e: print(f"āŒ Error uploading swimming workout: {e}") def _find_interval_step(steps: list[dict]) -> dict | None: """Return the first interval step, searching inside repeat groups.""" for step in steps: if step.get("stepType", {}).get("stepTypeKey") == "interval": return step nested = _find_interval_step(step.get("workoutSteps") or []) if nested: return nested return None def upload_swimming_css_workout_data(api: Garmin) -> None: """Upload a typed swimming workout with CSS-offset targets, then read it back.""" try: import sys from pathlib import Path test_data_path = Path(__file__).parent / "test_data" if str(test_data_path) not in sys.path: sys.path.insert(0, str(test_data_path)) from sample_swimming_workout import create_sample_swimming_css_workout print("šŸŠ Creating and uploading swimming workout with CSS +5s intervals...") workout = create_sample_swimming_css_workout() result = api.upload_swimming_workout(workout) if not result or not result.get("workoutId"): print("āŒ Failed to upload swimming CSS workout") return workout_id = result["workoutId"] print(f"āœ… Uploaded workout {workout_id}; reading it back from Garmin...") # Show what Garmin actually stored, so the CSS target can be checked # against what was sent (type 17 'swim.css.offset', value 5.0). # The upload already succeeded, so report a readback failure as such # rather than as an upload error that might prompt a duplicate upload. try: stored = api.get_workout_by_id(workout_id) except Exception as e: print( f"āš ļø Workout {workout_id} was uploaded, but reading it back failed: {e}" ) return steps = (stored.get("workoutSegments") or [{}])[0].get("workoutSteps") or [] interval = _find_interval_step(steps) if interval is None: print("āš ļø No interval step found in the stored workout") return call_and_display( lambda: { key: interval.get(key) for key in ( "targetType", "secondaryTargetType", "secondaryTargetValueOne", "secondaryTargetValueTwo", ) }, method_name="get_workout_by_id", api_call_desc=f"api.get_workout_by_id({workout_id}) - stored interval targets", ) print("šŸ’” Also open the workout in Garmin Connect to check it shows CSS +5s") except ImportError as e: print(f"āŒ Error: {e}") print( "šŸ’” Install pydantic with: pip install pydantic or pip install garminconnect[workout]" ) except Exception as e: print(f"āŒ Error uploading swimming CSS workout: {e}") def search_exercise_catalog_data(api: Garmin) -> None: """Search the bundled strength-exercise catalog.""" from garminconnect import exercises _ = api term = input("Enter exercise name or search term: ").strip() if not term: print("ā„¹ļø No search term entered") return exact = exercises.resolve(term) if exact: print(f"āœ… Exact match for '{term}':") print(f" category={exact['category']!r} exercise={exact['exercise']!r}") return matches = exercises.find(term) if not matches: print(f"āŒ No exercises found matching '{term}'") return print(f"šŸ” {len(matches)} exercise(s) matching '{term}' (showing up to 20):") for e in matches[:20]: print( f" {e['name']!r}: category={e['category']!r} exercise={e['exercise']!r}" ) def upload_strength_workout_data(api: Garmin) -> None: """Upload a typed strength workout.""" try: import sys from pathlib import Path # Add test_data to path for imports test_data_path = Path(__file__).parent / "test_data" if str(test_data_path) not in sys.path: sys.path.insert(0, str(test_data_path)) from sample_strength_workout import create_sample_strength_workout print("šŸ‹ļø Creating and uploading strength workout...") workout = create_sample_strength_workout() print(f"šŸ“¤ Uploading workout: {workout.workoutName}") result = api.upload_strength_workout(workout) if result: print("āœ… Strength workout uploaded successfully!") call_and_display( lambda: result, method_name="upload_strength_workout", api_call_desc="api.upload_strength_workout(workout)", ) else: print("āŒ Failed to upload strength workout") except ImportError as e: print(f"āŒ Error: {e}") print( "šŸ’” Install pydantic with: pip install pydantic or pip install garminconnect[workout]" ) except Exception as e: print(f"āŒ Error uploading strength workout: {e}") def _iter_exercise_steps(steps: list[dict]) -> list[dict]: """Return every interval (exercise) step, searching inside repeat groups.""" found: list[dict] = [] for step in steps: if step.get("stepType", {}).get("stepTypeKey") == "interval": found.append(step) found.extend(_iter_exercise_steps(step.get("workoutSteps") or [])) return found def upload_timed_strength_workout_data(api: Garmin) -> None: """Upload a strength workout with timed sets and step notes, then read it back.""" try: import sys from pathlib import Path test_data_path = Path(__file__).parent / "test_data" if str(test_data_path) not in sys.path: sys.path.insert(0, str(test_data_path)) from sample_strength_workout import create_sample_timed_strength_workout print("šŸ‹ļø Creating and uploading timed strength workout with step notes...") workout = create_sample_timed_strength_workout() result = api.upload_strength_workout(workout) if not result or not result.get("workoutId"): print("āŒ Failed to upload timed strength workout") return workout_id = result["workoutId"] print(f"āœ… Uploaded workout {workout_id}; reading it back from Garmin...") # Show what Garmin stored, so the time end condition and the step # descriptions can be checked against what was sent. try: stored = api.get_workout_by_id(workout_id) except Exception as e: print( f"āš ļø Workout {workout_id} was uploaded, but reading it back failed: {e}" ) return steps = (stored.get("workoutSegments") or [{}])[0].get("workoutSteps") or [] call_and_display( lambda: [ { "exercise": f"{s.get('category')}/{s.get('exerciseName')}", "endCondition": (s.get("endCondition") or {}).get( "conditionTypeKey" ), "endConditionValue": s.get("endConditionValue"), "description": s.get("description"), } for s in _iter_exercise_steps(steps) ], method_name="get_workout_by_id", api_call_desc=f"api.get_workout_by_id({workout_id}) - stored exercise steps", ) print( "šŸ’” Expect PLANK and FARMERS_CARRY with endCondition 'time' (45, 40) " "and BENCH_PRESS with 'reps' (10), each with its description" ) except ImportError as e: print(f"āŒ Error: {e}") print( "šŸ’” Install pydantic with: pip install pydantic or pip install garminconnect[workout]" ) except Exception as e: print(f"āŒ Error uploading timed strength workout: {e}") def schedule_workout_data(api: Garmin) -> None: """Schedule a workout on a specific date.""" try: workouts = api.get_workouts() if not workouts: print("ā„¹ļø No workouts found") return print("\nAvailable workouts (most recent):") for i, workout in enumerate(workouts[:10]): workout_id = workout.get("workoutId") workout_name = workout.get("workoutName", "Unknown") print(f" [{i}] {workout_name} (ID: {workout_id})") try: index_input = input( f"\nEnter workout index (0-{min(9, len(workouts) - 1)}, or 'q' to cancel): " ).strip() if index_input.lower() == "q": print("āŒ Cancelled") return workout_index = int(index_input) if not (0 <= workout_index < min(10, len(workouts))): print("āŒ Invalid index") return selected_workout = workouts[workout_index] workout_id = selected_workout["workoutId"] workout_name = selected_workout.get("workoutName", "Unknown") date_input = input( f"Enter date to schedule '{workout_name}' (YYYY-MM-DD, default: today): " ).strip() schedule_date = date_input if date_input else config.today.isoformat() call_and_display( api.schedule_workout, workout_id, schedule_date, method_name="schedule_workout", api_call_desc=f"api.schedule_workout({workout_id}, '{schedule_date}') - {workout_name}", ) print("āœ… Workout scheduled successfully!") except ValueError: print("āŒ Invalid input") except Exception as e: print(f"āŒ Error scheduling workout: {e}") def get_scheduled_workouts(api: Garmin) -> None: """Get scheduled workout by year and month.""" try: year_input = input("Enter year (YYYY): ").strip() month_input = input("Enter month (1-12): ").strip() if not year_input or not month_input: print("āŒ Year and month are required") return year = int(year_input) month = int(month_input) call_and_display( api.get_scheduled_workouts, year, month, method_name="get_scheduled_workouts", api_call_desc=f"api.get_scheduled_workouts({year}, {month})", ) except Exception as e: print(f"āŒ Error getting scheduled workouts by year and month: {e}") def get_next_scheduled_workout_data(api: Garmin) -> None: """Get the earliest upcoming scheduled workout (today or later).""" try: call_and_display( api.get_next_scheduled_workout, method_name="get_next_scheduled_workout", api_call_desc="api.get_next_scheduled_workout()", ) except Exception as e: print(f"āŒ Error getting next scheduled workout: {e}") def get_scheduled_workout_by_id_data(api: Garmin) -> None: """Get scheduled workout by ID.""" try: scheduled_workout_id = input("Enter scheduled workout ID: ").strip() if not scheduled_workout_id: print("āŒ Scheduled workout ID is required") return call_and_display( api.get_scheduled_workout_by_id, scheduled_workout_id, method_name="get_scheduled_workout_by_id", api_call_desc=f"api.get_scheduled_workout_by_id({scheduled_workout_id})", ) except Exception as e: print(f"āŒ Error getting scheduled workout by ID: {e}") def delete_workout_data(api: Garmin) -> None: """Delete a workout template from the library.""" try: workouts = api.get_workouts() if not workouts: print("ā„¹ļø No workouts found") return print("\nAvailable workouts (most recent):") for i, workout in enumerate(workouts[:10]): workout_id = workout.get("workoutId") workout_name = workout.get("workoutName", "Unknown") print(f" [{i}] {workout_name} (ID: {workout_id})") try: index_input = input( f"\nEnter workout index to delete (0-{min(9, len(workouts) - 1)}, or 'q' to cancel): " ).strip() if index_input.lower() == "q": print("āŒ Cancelled") return workout_index = int(index_input) if not (0 <= workout_index < min(10, len(workouts))): print("āŒ Invalid index") return selected_workout = workouts[workout_index] workout_id = selected_workout["workoutId"] workout_name = selected_workout.get("workoutName", "Unknown") confirm = input( f"Delete '{workout_name}' (ID: {workout_id})? (y/N): " ).strip() if confirm.lower() != "y": print("āŒ Cancelled") return call_and_display( api.delete_workout, workout_id, method_name="delete_workout", api_call_desc=f"api.delete_workout({workout_id}) - {workout_name}", ) print("āœ… Workout deleted successfully!") except ValueError: print("āŒ Invalid input") except Exception as e: print(f"āŒ Error deleting workout: {e}") def update_workout_data(api: Garmin) -> None: """Edit a workout in place (rename it) via update_workout.""" try: workouts = api.get_workouts() if not workouts: print("ā„¹ļø No workouts found") return print("\nAvailable workouts (most recent):") for i, workout in enumerate(workouts[:10]): workout_id = workout.get("workoutId") workout_name = workout.get("workoutName", "Unknown") print(f" [{i}] {workout_name} (ID: {workout_id})") try: index_input = input( f"\nEnter workout index to update (0-{min(9, len(workouts) - 1)}, or 'q' to cancel): " ).strip() if index_input.lower() == "q": print("āŒ Cancelled") return workout_index = int(index_input) if not (0 <= workout_index < min(10, len(workouts))): print("āŒ Invalid index") return selected_workout = workouts[workout_index] workout_id = selected_workout["workoutId"] # update_workout replaces the whole workout, so start from the full # structure rather than the summary returned by get_workouts() workout_data = api.get_workout_by_id(workout_id) original_name = workout_data.get("workoutName", "Workout") new_name = input( f"New name for '{original_name}' (blank to keep): " ).strip() if new_name: workout_data["workoutName"] = new_name call_and_display( api.update_workout, workout_id, workout_data, method_name="update_workout", api_call_desc=f"api.update_workout({workout_id}, workout_data)", ) print("āœ… Workout updated successfully!") except ValueError: print("āŒ Invalid input") except Exception as e: print(f"āŒ Error updating workout: {e}") def push_workout_to_device_data(api: Garmin) -> None: """Push a workout to a device, defaulting to the last workout/device.""" try: workouts = api.get_workouts() if not workouts: print("ā„¹ļø No workouts found") return print("\nAvailable workouts (most recent):") for i, workout in enumerate(workouts[:10]): workout_id = workout.get("workoutId") workout_name = workout.get("workoutName", "Unknown") print(f" [{i}] {workout_name} (ID: {workout_id})") index_input = input( f"\nEnter workout index to push (0-{min(9, len(workouts) - 1)}, " "blank for last workout, or 'q' to cancel): " ).strip() if index_input.lower() == "q": print("āŒ Cancelled") return workout_id = None if index_input: try: workout_index = int(index_input) except ValueError: print("āŒ Invalid input") return if not (0 <= workout_index < min(10, len(workouts))): print("āŒ Invalid index") return workout_id = workouts[workout_index]["workoutId"] devices = api.get_devices() device_id = None if devices: print("\nAvailable devices:") for i, device in enumerate(devices): d_id = device.get("deviceId") d_name = device.get("displayName", "Unknown") print(f" [{i}] {d_name} (ID: {d_id})") device_input = input( f"\nEnter device index (0-{len(devices) - 1}, " "blank for last used device): " ).strip() if device_input: try: device_index = int(device_input) except ValueError: print("āŒ Invalid input") return if not (0 <= device_index < len(devices)): print("āŒ Invalid index") return device_id = devices[device_index]["deviceId"] call_and_display( api.push_workout_to_device, workout_id, device_id, method_name="push_workout_to_device", api_call_desc=f"api.push_workout_to_device({workout_id}, {device_id})", ) print("āœ… Workout pushed to device successfully!") except Exception as e: print(f"āŒ Error pushing workout to device: {e}") def unschedule_workout_data(api: Garmin) -> None: """Remove a scheduled workout from the calendar.""" try: scheduled_id = input("Enter scheduled workout ID to unschedule: ").strip() if not scheduled_id: print("āŒ Scheduled workout ID is required") return call_and_display( api.unschedule_workout, scheduled_id, method_name="unschedule_workout", api_call_desc=f"api.unschedule_workout({scheduled_id})", ) print("āœ… Workout unscheduled successfully!") except Exception as e: print(f"āŒ Error unscheduling workout: {e}") def add_body_composition_data(api: Garmin) -> None: """Add body composition data.""" try: print(f"āš–ļø Adding body composition data for {config.today.isoformat()}") print("-" * 50) # Get weight input from user while True: try: weight_str = input( "Enter weight in kg (30-300, default: 85.1): " ).strip() if not weight_str: weight = 85.1 break weight = float(weight_str) if 30 <= weight <= 300: break print("āŒ Weight must be between 30 and 300 kg") except ValueError: print("āŒ Please enter a valid number") call_and_display( api.add_body_composition, config.today.isoformat(), weight=weight, percent_fat=15.4, percent_hydration=54.8, visceral_fat_mass=10.8, bone_mass=2.9, muscle_mass=55.2, basal_met=1454.1, active_met=None, physique_rating=None, metabolic_age=33.0, visceral_fat_rating=None, bmi=22.2, method_name="add_body_composition", api_call_desc=f"api.add_body_composition({config.today.isoformat()}, weight={weight}, ...)", ) print("āœ… Body composition data added successfully!") except Exception as e: print(f"āŒ Error adding body composition: {e}") def delete_weigh_ins_data(api: Garmin) -> None: """Delete all weigh-ins for today.""" try: call_and_display( api.delete_weigh_ins, config.today.isoformat(), delete_all=True, method_name="delete_weigh_ins", api_call_desc=f"api.delete_weigh_ins({config.today.isoformat()}, delete_all=True)", ) print("āœ… Weigh-ins deleted successfully!") except Exception as e: print(f"āŒ Error deleting weigh-ins: {e}") def delete_weigh_in_data(api: Garmin) -> None: """Delete a specific weigh-in.""" try: all_weigh_ins = [] # Find weigh-ins print(f"šŸ” Checking daily weigh-ins for today ({config.today.isoformat()})...") try: daily_weigh_ins = api.get_daily_weigh_ins(config.today.isoformat()) if daily_weigh_ins and "dateWeightList" in daily_weigh_ins: weight_list = daily_weigh_ins["dateWeightList"] for weigh_in in weight_list: if isinstance(weigh_in, dict): all_weigh_ins.append(weigh_in) print(f"šŸ“Š Found {len(all_weigh_ins)} weigh-in(s) for today") else: print("šŸ“Š No weigh-in data found in response") except Exception as e: print(f"āš ļø Could not fetch daily weigh-ins: {e}") if not all_weigh_ins: print("ā„¹ļø No weigh-ins found for today") print("šŸ’” You can add a test weigh-in using menu option [4]") return print(f"\nāš–ļø Found {len(all_weigh_ins)} weigh-in(s) available for deletion:") print("-" * 70) # Display weigh-ins for user selection for i, weigh_in in enumerate(all_weigh_ins): # Extract weight data - Garmin API uses different field names weight = weigh_in.get("weight") if weight is None: weight = weigh_in.get("weightValue", "Unknown") # Convert weight from grams to kg if it's a number if isinstance(weight, int | float) and weight > 1000: weight = weight / 1000 # Convert from grams to kg weight = round(weight, 1) # Round to 1 decimal place unit = weigh_in.get("unitKey", "kg") date = weigh_in.get("calendarDate", config.today.isoformat()) # Try different timestamp fields timestamp = ( weigh_in.get("timestampGMT") or weigh_in.get("timestamp") or weigh_in.get("date") ) # Format timestamp for display if timestamp: try: import datetime as dt if isinstance(timestamp, str): # Handle ISO format strings datetime_obj = dt.datetime.fromisoformat( timestamp.replace("Z", "+00:00") ) else: # Handle millisecond timestamps datetime_obj = dt.datetime.fromtimestamp(timestamp / 1000) time_str = datetime_obj.strftime("%H:%M:%S") except Exception: time_str = "Unknown time" else: time_str = "Unknown time" print(f" [{i}] {weight} {unit} on {date} at {time_str}") print() try: selection = input( "Enter the index of the weigh-in to delete (or 'q' to cancel): " ).strip() if selection.lower() == "q": print("āŒ Delete cancelled") return weigh_in_index = int(selection) if 0 <= weigh_in_index < len(all_weigh_ins): selected_weigh_in = all_weigh_ins[weigh_in_index] # Get the weigh-in ID (Garmin uses 'samplePk' as the primary key) weigh_in_id = ( selected_weigh_in.get("samplePk") or selected_weigh_in.get("id") or selected_weigh_in.get("weightPk") or selected_weigh_in.get("pk") or selected_weigh_in.get("weightId") or selected_weigh_in.get("uuid") ) if weigh_in_id: weight = selected_weigh_in.get("weight", "Unknown") # Convert weight from grams to kg if it's a number if isinstance(weight, int | float) and weight > 1000: weight = weight / 1000 # Convert from grams to kg weight = round(weight, 1) # Round to 1 decimal place unit = selected_weigh_in.get("unitKey", "kg") date = selected_weigh_in.get( "calendarDate", config.today.isoformat() ) # Confirm deletion confirm = input( f"Delete weigh-in {weight} {unit} from {date}? (yes/no): " ).lower() if confirm == "yes": call_and_display( api.delete_weigh_in, weigh_in_id, config.today.isoformat(), method_name="delete_weigh_in", api_call_desc=f"api.delete_weigh_in({weigh_in_id}, {config.today.isoformat()})", ) print("āœ… Weigh-in deleted successfully!") else: print("āŒ Delete cancelled") else: print("āŒ No weigh-in ID found for selected entry") else: print("āŒ Invalid selection") except ValueError: print("āŒ Invalid input - please enter a number") except Exception as e: print(f"āŒ Error deleting weigh-in: {e}") def get_device_settings_data(api: Garmin) -> None: """Get device settings for all devices.""" try: devices = api.get_devices() if devices: for device in devices: device_id = device["deviceId"] device_name = device.get("displayName", f"Device {device_id}") try: call_and_display( api.get_device_settings, device_id, method_name="get_device_settings", api_call_desc=f"api.get_device_settings({device_id}) - {device_name}", ) except Exception as e: print(f"āŒ Error getting settings for device {device_name}: {e}") else: print("ā„¹ļø No devices found") except Exception as e: print(f"āŒ Error getting device settings: {e}") def get_gear_data(api: Garmin) -> None: """Get user gear list.""" print("šŸ”„ Fetching user gear list...") api_responses = [] # Get device info first api_responses.append( safe_call_for_group( api.get_device_last_used, method_name="get_device_last_used", api_call_desc="api.get_device_last_used()", ) ) # Get user profile number from the first call device_success, device_data, _ = safe_api_call( api.get_device_last_used, method_name="get_device_last_used" ) if device_success and device_data: user_profile_number = device_data.get("userProfileNumber") if user_profile_number: api_responses.append( safe_call_for_group( api.get_gear, user_profile_number, method_name="get_gear", api_call_desc=f"api.get_gear({user_profile_number})", ) ) else: print("āŒ Could not get user profile number") call_and_display(group_name="User Gear List", api_responses=api_responses) def get_gear_defaults_data(api: Garmin) -> None: """Get gear defaults.""" print("šŸ”„ Fetching gear defaults...") api_responses = [] # Get device info first api_responses.append( safe_call_for_group( api.get_device_last_used, method_name="get_device_last_used", api_call_desc="api.get_device_last_used()", ) ) # Get user profile number from the first call device_success, device_data, _ = safe_api_call( api.get_device_last_used, method_name="get_device_last_used" ) if device_success and device_data: user_profile_number = device_data.get("userProfileNumber") if user_profile_number: api_responses.append( safe_call_for_group( api.get_gear_defaults, user_profile_number, method_name="get_gear_defaults", api_call_desc=f"api.get_gear_defaults({user_profile_number})", ) ) else: print("āŒ Could not get user profile number") call_and_display(group_name="Gear Defaults", api_responses=api_responses) def get_gear_stats_data(api: Garmin) -> None: """Get gear statistics.""" print("šŸ”„ Fetching comprehensive gear statistics...") api_responses = [] # Get device info first api_responses.append( safe_call_for_group( api.get_device_last_used, method_name="get_device_last_used", api_call_desc="api.get_device_last_used()", ) ) # Get user profile number and gear list device_success, device_data, _ = safe_api_call( api.get_device_last_used, method_name="get_device_last_used" ) if device_success and device_data: user_profile_number = device_data.get("userProfileNumber") if user_profile_number: # Get gear list api_responses.append( safe_call_for_group( api.get_gear, user_profile_number, method_name="get_gear", api_call_desc=f"api.get_gear({user_profile_number})", ) ) # Get gear data to extract UUIDs for stats gear_success, gear_data, _ = safe_api_call( api.get_gear, user_profile_number, method_name="get_gear" ) if gear_success and gear_data: # Get stats for each gear item (limit to first 3) for gear_item in gear_data[:3]: gear_uuid = gear_item.get("uuid") gear_name = gear_item.get("displayName", "Unknown") if gear_uuid: api_responses.append( safe_call_for_group( api.get_gear_stats, gear_uuid, method_name="get_gear_stats", api_call_desc=f"api.get_gear_stats('{gear_uuid}') - {gear_name}", ) ) else: print("ā„¹ļø No gear found") else: print("āŒ Could not get user profile number") call_and_display(group_name="Gear Statistics", api_responses=api_responses) def get_gear_activities_data(api: Garmin) -> None: """Get gear activities.""" print("šŸ”„ Fetching gear activities...") api_responses = [] # Get device info first api_responses.append( safe_call_for_group( api.get_device_last_used, method_name="get_device_last_used", api_call_desc="api.get_device_last_used()", ) ) # Get user profile number and gear list device_success, device_data, _ = safe_api_call( api.get_device_last_used, method_name="get_device_last_used" ) if device_success and device_data: user_profile_number = device_data.get("userProfileNumber") if user_profile_number: # Get gear list api_responses.append( safe_call_for_group( api.get_gear, user_profile_number, method_name="get_gear", api_call_desc=f"api.get_gear({user_profile_number})", ) ) # Get gear data to extract UUID for activities gear_success, gear_data, _ = safe_api_call( api.get_gear, user_profile_number, method_name="get_gear" ) if gear_success and gear_data and len(gear_data) > 0: # Get activities for the first gear item gear_uuid = gear_data[0].get("uuid") gear_name = gear_data[0].get("displayName", "Unknown") if gear_uuid: api_responses.append( safe_call_for_group( api.get_gear_activities, gear_uuid, method_name="get_gear_activities", api_call_desc=f"api.get_gear_activities('{gear_uuid}') - {gear_name}", ) ) else: print("āŒ No gear UUID found") else: print("ā„¹ļø No gear found") else: print("āŒ Could not get user profile number") call_and_display(group_name="Gear Activities", api_responses=api_responses) def set_gear_default_data(api: Garmin) -> None: """Set gear default.""" try: device_last_used = api.get_device_last_used() user_profile_number = device_last_used.get("userProfileNumber") if user_profile_number: gear = api.get_gear(user_profile_number) if gear: gear_uuid = gear[0].get("uuid") gear_name = gear[0].get("displayName", "Unknown") if gear_uuid: # Set as default for running (activity type ID 1) # Correct method signature: set_gear_default(activityType, gearUUID, defaultGear=True) activity_type = 1 # Running call_and_display( api.set_gear_default, activity_type, gear_uuid, True, method_name="set_gear_default", api_call_desc=f"api.set_gear_default({activity_type}, '{gear_uuid}', True) - {gear_name} for running", ) print("āœ… Gear default set successfully!") else: print("āŒ No gear UUID found") else: print("ā„¹ļø No gear found") else: print("āŒ Could not get user profile number") except Exception as e: print(f"āŒ Error setting gear default: {e}") def add_and_remove_gear_to_activity(api: Garmin) -> None: """Add gear to most recent activity, then remove.""" try: device_last_used = api.get_device_last_used() user_profile_number = device_last_used.get("userProfileNumber") if user_profile_number: gear_list = api.get_gear(user_profile_number) if gear_list: activities = api.get_activities(0, 1) if activities: activity_id = activities[0].get("activityId") activity_name = activities[0].get("activityName") for gear in gear_list: if gear["gearStatusName"] == "active": break gear_uuid = gear.get("uuid") gear_name = gear.get("displayName", "Unknown") if gear_uuid: # Add gear to an activity # Correct method signature: add_gear_to_activity(gearUUID, activity_id) call_and_display( api.add_gear_to_activity, gear_uuid, activity_id, method_name="add_gear_to_activity", api_call_desc=f"api.add_gear_to_activity('{gear_uuid}', {activity_id}) - Add {gear_name} to {activity_name}", ) print("āœ… Gear added successfully!") # Wait for user to check gear, then continue input( "Go check Garmin to confirm, then press Enter to continue" ) # Remove gear from an activity # Correct method signature: remove_gear_from_activity(gearUUID, activity_id) call_and_display( api.remove_gear_from_activity, gear_uuid, activity_id, method_name="remove_gear_from_activity", api_call_desc=f"api.remove_gear_from_activity('{gear_uuid}', {activity_id}) - Remove {gear_name} from {activity_name}", ) print("āœ… Gear removed successfully!") else: print("āŒ No activities found") else: print("āŒ No gear UUID found") else: print("ā„¹ļø No gear found") else: print("āŒ Could not get user profile number") except Exception as e: print(f"āŒ Error adding gear: {e}") def get_activities_filtered_data(api: Garmin) -> None: """Get activities filtered by type/subtype, picked from the account's own activity type list.""" try: activity_types = api.get_activity_types() print("\nAvailable activity types:") for i, activity_type in enumerate(activity_types): print( f"{i}: {activity_type.get('typeKey', 'Unknown')} - {activity_type.get('display', 'No description')}" ) type_index = input( "\nEnter activity type index to filter by (blank for no filter): " ).strip() activitytype = None if type_index: try: idx = int(type_index) if 0 <= idx < len(activity_types): activitytype = activity_types[idx]["typeKey"] else: print("āŒ Invalid index, no type filter applied") except ValueError: print("āŒ Invalid index, no type filter applied") activitysubtype = None if activitytype: hint = ( " (e.g. 'strength_training')" if activitytype == "fitness_equipment" else "" ) activitysubtype = ( input(f"Activity subtype{hint} (blank for none): ").strip() or None ) call_and_display( api.get_activities, config.start, config.default_limit, activitytype=activitytype, activitysubtype=activitysubtype, method_name="get_activities_filtered", api_call_desc=( f"api.get_activities({config.start}, {config.default_limit}, " f"activitytype={activitytype!r}, activitysubtype={activitysubtype!r})" ), ) except Exception as e: print(f"āŒ Error getting filtered activities: {e}") def create_gear_data(api: Garmin) -> None: """Create a new piece of gear, e.g. a pair of shoes.""" try: print("Creating new gear...") print("Enter gear details (press Enter for defaults):") gear_type = input("Gear type [SHOES]: ").strip() or "SHOES" brand = input("Brand [Anta]: ").strip() or "Anta" model = input("Model [A-Flash]: ").strip() or "A-Flash" name = input("Nickname [Test]: ").strip() or "Test" first_use_date = ( input(f"First use date [{config.today.isoformat()}]: ").strip() or config.today.isoformat() ) usage_type = input("Usage tracking type [DISTANCE]: ").strip() or "DISTANCE" max_km = input("Max use threshold in km (blank for none): ").strip() activity_types_input = input( "Default activity types, comma-separated [running]: " ).strip() activity_type_keys = [ key.strip() for key in (activity_types_input or "running").split(",") if key.strip() ] notes = input("Notes (blank for none): ").strip() try: max_usage_distance_km = float(max_km) if max_km else None success, _ = call_and_display( api.create_gear, gear_type=gear_type, brand=brand, model=model, name=name, first_use_date=first_use_date, usage_type=usage_type, max_usage_distance_km=max_usage_distance_km, notes=notes, activity_type_keys=activity_type_keys, method_name="create_gear", api_call_desc=( f"api.create_gear(gear_type='{gear_type}', brand='{brand}', " f"model='{model}', name='{name}', " f"first_use_date='{first_use_date}', usage_type='{usage_type}', " f"max_usage_distance_km={max_usage_distance_km}, " f"activity_type_keys={activity_type_keys})" ), ) if success: print("āœ… Gear created!") except ValueError: print("āŒ Invalid numeric input") except Exception as e: print(f"āŒ Error creating gear: {e}") def _format_record_duration(seconds: float) -> str: """Format a personal-record time value (seconds) as h:mm:ss or m:ss.""" total = round(seconds) hours, remainder = divmod(total, 3600) minutes, secs = divmod(remainder, 60) if hours: return f"{hours}:{minutes:02d}:{secs:02d}" return f"{minutes}:{secs:02d}" def _format_record_distance(meters: float) -> str: """Format a personal-record distance value (meters) as km.""" return f"{meters / 1000:.2f} km" def _format_record_count(value: float) -> str: """Format a personal-record count value (e.g. steps) with thousands separators.""" return f"{round(value):,}" def _format_record_days(value: float) -> str: """Format a personal-record day-count value (e.g. a goal streak).""" days = round(value) return f"{days} day" if days == 1 else f"{days} days" _RECORD_FORMATTERS = { "time": _format_record_duration, "distance": _format_record_distance, "count": _format_record_count, "days": _format_record_days, } def get_personal_records_data(api: Garmin) -> None: """Get personal records, decoding typeId into a human-readable label and value, and optionally looking up the source activity's details (needed for longest-run duration, which isn't included in the personal-record entry itself). Two typeId ranges are confirmed against a real account's Garmin Connect "Personal Records" page: - activityType == "running": typeIds 1-6 are best-time records for a fixed distance (value is a duration in seconds), typeId 7 is a distance record (value is meters). - activityType is None: typeIds 12-14 are step counts (day/week/ month), 15-16 are goal-streak day counts. Anything else is shown as an unconfirmed raw value — check the Garmin Connect "Personal Records" page for what it actually is rather than trusting a guess here. """ # (label, formatter key) — see _RECORD_FORMATTERS. Confirmed against a # real account; see docstring. running_type_info = { 1: ("1 km", "time"), 2: ("1 mile", "time"), 3: ("5 km", "time"), 4: ("10 km", "time"), 5: ("Half marathon", "time"), 6: ("Marathon", "time"), 7: ("Longest run", "distance"), } # activityType is None for these — steps/streak records, not tied to a # specific sport. other_type_info = { 12: ("Most steps in a day", "count"), 13: ("Most steps in a week", "count"), 14: ("Most steps in a month", "count"), 15: ("Longest goal streak", "days"), 16: ("Current goal streak", "days"), } try: success, records = call_and_display( api.get_personal_record, method_name="get_personal_record", api_call_desc="api.get_personal_record()", ) if not success or not records: return entries = records if isinstance(records, list) else [records] if not entries: print("ā„¹ļø No personal records found") return print("\nPersonal records:") for i, entry in enumerate(entries): type_id = entry.get("typeId") activity_type = entry.get("activityType") value = entry.get("value") if activity_type == "running": info = running_type_info.get(type_id) elif activity_type is None: info = other_type_info.get(type_id) else: info = None if info is not None and isinstance(value, int | float): label, kind = info formatted = _RECORD_FORMATTERS[kind](value) print( f"{i}: {label} — {formatted} (typeId={type_id}, raw value={value})" ) else: print( f"{i}: Unconfirmed record type " f"(typeId={type_id}, activityType={activity_type!r}, raw value={value})" ) choice = input( "\nEnter index to look up the source activity's details (blank to skip): " ).strip() if not choice: return try: idx = int(choice) if not (0 <= idx < len(entries)): print("āŒ Invalid index") return except ValueError: print("āŒ Invalid index") return activity_id = entries[idx].get("activityId") or entries[idx].get( "activityIdInt" ) if not activity_id: print("ā„¹ļø This record entry has no activityId to look up") return call_and_display( api.get_activity, str(activity_id), method_name="get_activity", api_call_desc=f"api.get_activity('{activity_id}')", ) except Exception as e: print(f"āŒ Error getting personal records: {e}") def set_activity_name_data(api: Garmin) -> None: """Set activity name.""" try: activities = api.get_activities(0, 1) if activities: activity_id = activities[0]["activityId"] print(f"Current name of fetched activity: {activities[0]['activityName']}") new_name = input("Enter new activity name: (or 'q' to cancel): ").strip() if new_name.lower() == "q": print("āŒ Rename cancelled") return if new_name: call_and_display( api.set_activity_name, activity_id, new_name, method_name="set_activity_name", api_call_desc=f"api.set_activity_name({activity_id}, '{new_name}')", ) print("āœ… Activity name updated!") else: print("āŒ No name provided") else: print("āŒ No activities found") except Exception as e: print(f"āŒ Error setting activity name: {e}") def set_activity_type_data(api: Garmin) -> None: """Set activity type.""" try: activities = api.get_activities(0, 1) if activities: activity_id = activities[0]["activityId"] activity_types = api.get_activity_types() # Show available types print("\nAvailable activity types: (limit=10)") for i, activity_type in enumerate(activity_types[:10]): # Show first 10 print( f"{i}: {activity_type.get('typeKey', 'Unknown')} - {activity_type.get('display', 'No description')}" ) try: print( f"Current type of fetched activity '{activities[0]['activityName']}': {activities[0]['activityType']['typeKey']}" ) type_index = input( "Enter activity type index: (or 'q' to cancel): " ).strip() if type_index.lower() == "q": print("āŒ Type change cancelled") return type_index = int(type_index) if 0 <= type_index < len(activity_types): selected_type = activity_types[type_index] type_id = selected_type["typeId"] type_key = selected_type["typeKey"] parent_type_id = selected_type.get( "parentTypeId", selected_type["typeId"] ) call_and_display( api.set_activity_type, activity_id, type_id, type_key, parent_type_id, method_name="set_activity_type", api_call_desc=f"api.set_activity_type({activity_id}, {type_id}, '{type_key}', {parent_type_id})", ) print("āœ… Activity type updated!") else: print("āŒ Invalid index") except ValueError: print("āŒ Invalid input") else: print("āŒ No activities found") except Exception as e: print(f"āŒ Error setting activity type: {e}") def set_activity_description_data(api: Garmin) -> None: """Set the description of the most recent activity.""" try: activities = api.get_activities(0, 1) if not activities: print("āŒ No activities found") return activity = activities[0] activity_id = activity["activityId"] current = activity.get("description") or "(none)" print(f"Activity: {activity.get('activityName')} (id {activity_id})") print(f"Current description: {current}") new_desc = input("Enter new description (or 'q' to cancel): ").strip() if new_desc.lower() == "q": print("āŒ Cancelled") return call_and_display( api.set_activity_description, activity_id, new_desc, method_name="set_activity_description", api_call_desc=f"api.set_activity_description({activity_id}, '{new_desc}')", ) print("āœ… Activity description updated!") except Exception as e: print(f"āŒ Error setting activity description: {e}") def set_activity_exercise_sets_data(api: Garmin) -> None: """Replace exercise sets on a strength-training activity. Demonstrates the round-trip: fetch the current sets, then re-submit the exact same payload (replace-all semantics). Re-submitting unchanged data is a safe no-op that proves the endpoint without altering the activity. """ try: activities = api.get_activities( 0, 1, activitytype="fitness_equipment", activitysubtype="strength_training" ) activity_list = ( activities.get("activityList", []) if isinstance(activities, dict) else activities ) strength_activity = activity_list[0] if activity_list else None if not strength_activity: print("ā„¹ļø No strength training activities found") return activity_id = strength_activity["activityId"] current = api.get_activity_exercise_sets(activity_id) sets = current.get("exerciseSets") if isinstance(current, dict) else None if not sets: print(f"ā„¹ļø Activity {activity_id} has no exercise sets to replace") return print(f"Activity {activity_id} has {len(sets)} exercise set(s).") print( "āš ļø This REPLACES all exercise sets (replace-all). The demo re-submits " "the same payload unchanged, so nothing actually changes." ) confirm = input("Re-submit current sets? (yes/no): ").strip().lower() if confirm != "yes": print("āŒ Cancelled") return call_and_display( api.set_activity_exercise_sets, activity_id, {"exerciseSets": sets}, method_name="set_activity_exercise_sets", api_call_desc=( f"api.set_activity_exercise_sets({activity_id}, " f"{{'exerciseSets': <{len(sets)} sets>}})" ), ) print("āœ… Exercise sets submitted!") except Exception as e: print(f"āŒ Error setting exercise sets: {e}") def create_manual_activity_data(api: Garmin) -> None: """Create manual activity.""" try: print("Creating manual activity...") print("Enter activity details (press Enter for defaults):") activity_name = ( input("Activity name [Manual Activity]: ").strip() or "Manual Activity" ) type_key = input("Activity type key [running]: ").strip() or "running" duration_min = input("Duration in minutes [60]: ").strip() or "60" distance_km = input("Distance in kilometers [5]: ").strip() or "5" timezone = input("Timezone [UTC]: ").strip() or "UTC" try: duration_min = float(duration_min) distance_km = float(distance_km) # Use the current time as start time import datetime start_datetime = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%S.00") call_and_display( api.create_manual_activity, start_datetime=start_datetime, time_zone=timezone, type_key=type_key, distance_km=distance_km, duration_min=duration_min, activity_name=activity_name, method_name="create_manual_activity", api_call_desc=f"api.create_manual_activity(start_datetime='{start_datetime}', time_zone='{timezone}', type_key='{type_key}', distance_km={distance_km}, duration_min={duration_min}, activity_name='{activity_name}')", ) print("āœ… Manual activity created!") except ValueError: print("āŒ Invalid numeric input") except Exception as e: print(f"āŒ Error creating manual activity: {e}") def delete_activity_data(api: Garmin) -> None: """Delete activity.""" try: activities = api.get_activities(0, 5) if activities: print("\nRecent activities:") for i, activity in enumerate(activities): activity_name = activity.get("activityName", "Unnamed") activity_id = activity.get("activityId") start_time = activity.get("startTimeLocal", "Unknown time") print(f"{i}: {activity_name} ({activity_id}) - {start_time}") try: activity_index = input( "Enter activity index to delete: (or 'q' to cancel): " ).strip() if activity_index.lower() == "q": print("āŒ Delete cancelled") return activity_index = int(activity_index) if 0 <= activity_index < len(activities): activity_id = activities[activity_index]["activityId"] activity_name = activities[activity_index].get( "activityName", "Unnamed" ) confirm = input(f"Delete '{activity_name}'? (yes/no): ").lower() if confirm == "yes": call_and_display( api.delete_activity, activity_id, method_name="delete_activity", api_call_desc=f"api.delete_activity({activity_id})", ) print("āœ… Activity deleted!") else: print("āŒ Delete cancelled") else: print("āŒ Invalid index") except ValueError: print("āŒ Invalid input") else: print("āŒ No activities found") except Exception as e: print(f"āŒ Error deleting activity: {e}") def delete_blood_pressure_data(api: Garmin) -> None: """Delete blood pressure entry.""" try: # Get recent blood pressure entries bp_data = api.get_blood_pressure( config.week_start.isoformat(), config.today.isoformat() ) entry_list = [] # Parse the actual blood pressure data structure if bp_data and bp_data.get("measurementSummaries"): for summary in bp_data["measurementSummaries"]: if summary.get("measurements"): for measurement in summary["measurements"]: # Use 'version' as the identifier (this is what Garmin uses) entry_id = measurement.get("version") systolic = measurement.get("systolic") diastolic = measurement.get("diastolic") pulse = measurement.get("pulse") timestamp = measurement.get("measurementTimestampLocal") notes = measurement.get("notes", "") # Extract date for deletion API (format: YYYY-MM-DD) measurement_date = None if timestamp: try: measurement_date = timestamp.split("T")[ 0 ] # Get just the date part except Exception: measurement_date = summary.get( "startDate" ) # Fallback to summary date else: measurement_date = summary.get( "startDate" ) # Fallback to summary date if entry_id and systolic and diastolic and measurement_date: # Format display text with more details display_parts = [f"{systolic}/{diastolic}"] if pulse: display_parts.append(f"pulse {pulse}") if timestamp: display_parts.append(f"at {timestamp}") if notes: display_parts.append(f"({notes})") display_text = " ".join(display_parts) # Store both entry_id and measurement_date for deletion entry_list.append( (entry_id, display_text, measurement_date) ) if entry_list: print(f"\nšŸ“Š Found {len(entry_list)} blood pressure entries:") print("-" * 70) for i, (entry_id, display_text, _measurement_date) in enumerate(entry_list): print(f" [{i}] {display_text} (ID: {entry_id})") try: entry_index = input( "\nEnter entry index to delete: (or 'q' to cancel): " ).strip() if entry_index.lower() == "q": print("āŒ Entry deletion cancelled") return entry_index = int(entry_index) if 0 <= entry_index < len(entry_list): entry_id, display_text, measurement_date = entry_list[entry_index] confirm = input( f"Delete entry '{display_text}'? (yes/no): " ).lower() if confirm == "yes": call_and_display( api.delete_blood_pressure, entry_id, measurement_date, method_name="delete_blood_pressure", api_call_desc=f"api.delete_blood_pressure('{entry_id}', '{measurement_date}')", ) print("āœ… Blood pressure entry deleted!") else: print("āŒ Delete cancelled") else: print("āŒ Invalid index") except ValueError: print("āŒ Invalid input") else: print("āŒ No blood pressure entries found for past week") print("šŸ’” You can add a test measurement using menu option [3]") except Exception as e: print(f"āŒ Error deleting blood pressure: {e}") def query_garmin_graphql_data(api: Garmin) -> None: """Execute GraphQL query with a menu of available queries.""" try: print("Available GraphQL queries:") print(" [1] Activities (recent activities with details)") print(" [2] Health Snapshot (comprehensive health data)") print(" [3] Weight Data (weight measurements)") print(" [4] Blood Pressure (blood pressure data)") print(" [5] Sleep Summaries (sleep analysis)") print(" [6] Heart Rate Variability (HRV data)") print(" [7] User Daily Summary (comprehensive daily stats)") print(" [8] Training Readiness (training readiness metrics)") print(" [9] Training Status (training status data)") print(" [10] Activity Stats (aggregated activity statistics)") print(" [11] VO2 Max (VO2 max data)") print(" [12] Endurance Score (endurance scoring)") print(" [13] User Goals (current goals)") print(" [14] Stress Data (epoch chart with stress)") print(" [15] Badge Challenges (available challenges)") print(" [16] Adhoc Challenges (adhoc challenges)") print(" [c] Custom query") choice = input("\nEnter choice (1-16, c): ").strip() # Use today's date and date range for queries that need them today = config.today.isoformat() week_start = config.week_start.isoformat() start_datetime = f"{today}T00:00:00.00" end_datetime = f"{today}T23:59:59.999" if choice == "1": query = f'query{{activitiesScalar(displayName:"{api.display_name}", startTimestampLocal:"{start_datetime}", endTimestampLocal:"{end_datetime}", limit:10)}}' elif choice == "2": query = f'query{{healthSnapshotScalar(startDate:"{week_start}", endDate:"{today}")}}' elif choice == "3": query = ( f'query{{weightScalar(startDate:"{week_start}", endDate:"{today}")}}' ) elif choice == "4": query = f'query{{bloodPressureScalar(startDate:"{week_start}", endDate:"{today}")}}' elif choice == "5": query = f'query{{sleepSummariesScalar(startDate:"{week_start}", endDate:"{today}")}}' elif choice == "6": query = f'query{{heartRateVariabilityScalar(startDate:"{week_start}", endDate:"{today}")}}' elif choice == "7": query = f'query{{userDailySummaryV2Scalar(startDate:"{week_start}", endDate:"{today}")}}' elif choice == "8": query = f'query{{trainingReadinessRangeScalar(startDate:"{week_start}", endDate:"{today}")}}' elif choice == "9": query = f'query{{trainingStatusDailyScalar(calendarDate:"{today}")}}' elif choice == "10": query = f'query{{activityStatsScalar(aggregation:"daily", startDate:"{week_start}", endDate:"{today}", metrics:["duration", "distance"], groupByParentActivityType:true, standardizedUnits:true)}}' elif choice == "11": query = ( f'query{{vo2MaxScalar(startDate:"{week_start}", endDate:"{today}")}}' ) elif choice == "12": query = f'query{{enduranceScoreScalar(startDate:"{week_start}", endDate:"{today}", aggregation:"weekly")}}' elif choice == "13": query = "query{userGoalsScalar}" elif choice == "14": query = f'query{{epochChartScalar(date:"{today}", include:["stress"])}}' elif choice == "15": query = "query{badgeChallengesScalar}" elif choice == "16": query = "query{adhocChallengesScalar}" elif choice.lower() == "c": print("\nEnter your custom GraphQL query:") print("Example: query{userGoalsScalar}") query = input("Query: ").strip() else: print("āŒ Invalid choice") return if query: # GraphQL API expects a dictionary with the query as a string value graphql_payload = {"query": query} call_and_display( api.query_garmin_graphql, graphql_payload, method_name="query_garmin_graphql", api_call_desc=f"api.query_garmin_graphql({graphql_payload})", ) else: print("āŒ No query provided") except Exception as e: print(f"āŒ Error executing GraphQL query: {e}") def get_virtual_challenges_data(api: Garmin) -> None: """Get virtual challenges data with centralized error handling.""" print("šŸ† Attempting to get virtual challenges data...") # Try in-progress virtual challenges - this endpoint often returns 400 for accounts # that don't have virtual challenges enabled, so handle it quietly try: challenges = api.get_inprogress_virtual_challenges( config.start_badge, config.default_limit ) if challenges: print("āœ… Virtual challenges data retrieved successfully") call_and_display( api.get_inprogress_virtual_challenges, config.start_badge, config.default_limit, method_name="get_inprogress_virtual_challenges", api_call_desc=f"api.get_inprogress_virtual_challenges({config.start_badge}, {config.default_limit})", ) return print("ā„¹ļø No in-progress virtual challenges found") return except GarminConnectConnectionError as e: # Handle the common 400 error case quietly - this is expected for many accounts error_str = str(e) if "400" in error_str and ( "Bad Request" in error_str or "API client error" in error_str ): print("ā„¹ļø Virtual challenges are not available for your account") else: # For unexpected connection errors, show them print(f"āš ļø Connection error accessing virtual challenges: {error_str}") except Exception as e: print(f"āš ļø Unexpected error accessing virtual challenges: {e}") # Since virtual challenges failed or returned no data, suggest alternatives print("šŸ’” You can try other challenge-related endpoints instead:") print(" - Badge challenges (menu option 7-8)") print(" - Available badge challenges (menu option 7-4)") print(" - Adhoc challenges (menu option 7-3)") def add_hydration_data_entry(api: Garmin) -> None: """Add hydration data entry.""" try: import datetime value_in_ml = 240 raw_date = config.today cdate = str(raw_date) raw_ts = datetime.datetime.now() timestamp = datetime.datetime.strftime(raw_ts, "%Y-%m-%dT%H:%M:%S.%f") call_and_display( api.add_hydration_data, value_in_ml=value_in_ml, cdate=cdate, timestamp=timestamp, method_name="add_hydration_data", api_call_desc=f"api.add_hydration_data(value_in_ml={value_in_ml}, cdate='{cdate}', timestamp='{timestamp}')", ) print("āœ… Hydration data added successfully!") except Exception as e: print(f"āŒ Error adding hydration data: {e}") def _parse_csv_enums(raw: str) -> list[str] | None: raw = raw.strip() if not raw: return None return [part.strip() for part in raw.split(",") if part.strip()] def update_menstrual_daily_log_entry(api: Garmin) -> None: """Write a menstrual daily-log snapshot.""" try: print("Omitted lists/scalars are cleared. Omitted notes are kept.") print("Use a single '-' for notes to clear existing notes.") calendar_date = ( input(f"Date [{config.today.isoformat()}]: ").strip() or config.today.isoformat() ) symptoms = _parse_csv_enums(input("Symptoms (comma-separated): ")) moods = _parse_csv_enums(input("Moods (comma-separated): ")) flow = input("Flow [LIGHT|MEDIUM|HEAVY, empty omit]: ").strip() or None discharge = _parse_csv_enums(input("Discharge (comma-separated): ")) sex_drive = input("Sex drive [LOW|AVERAGE|HIGH, empty omit]: ").strip() or None sexual_activity = ( input("Sexual activity [PROTECTED|UNPROTECTED, empty omit]: ").strip() or None ) notes_raw = input("Notes (empty keep, '-' clear): ") if notes_raw == "": notes = None elif notes_raw.strip() == "-": notes = "" else: notes = notes_raw ovulation_raw = input("Ovulation day? [y/N]: ").strip().lower() ovulation_day = True if ovulation_raw == "y" else None call_and_display( api.update_menstrual_daily_log, calendar_date, symptoms=symptoms, moods=moods, flow=flow, discharge=discharge, sex_drive=sex_drive, sexual_activity=sexual_activity, notes=notes, ovulation_day=ovulation_day, method_name="update_menstrual_daily_log", api_call_desc=(f"api.update_menstrual_daily_log('{calendar_date}', ...)"), ) except Exception as e: print(f"āŒ Error updating menstrual daily log: {e}") def update_menstrual_calendar_entry(api: Garmin) -> None: """Replace period dates on the menstrual calendar.""" try: print("Do not post predicted cycles as confirmed period dates.") print("Enter period groups as comma-separated dates, groups separated by ';'.") startdate = input("Start date (YYYY-MM-DD): ").strip() enddate = input("End date (YYYY-MM-DD): ").strip() raw_groups = input("Period date groups: ").strip() cycle_dates_lists = [ [day.strip() for day in group.split(",") if day.strip()] for group in raw_groups.split(";") if group.strip() ] call_and_display( api.update_menstrual_calendar, startdate, enddate, cycle_dates_lists, method_name="update_menstrual_calendar", api_call_desc=( "api.update_menstrual_calendar(" f"'{startdate}', '{enddate}', {cycle_dates_lists})" ), ) except Exception as e: print(f"āŒ Error updating menstrual calendar: {e}") def init_menstrual_cycle_setup_entry(api: Garmin) -> None: """Initialize menstrual cycle tracking (first-run only).""" try: period_start_date = input("Period start date (YYYY-MM-DD): ").strip() period_length = int(input("Period length (days): ").strip()) cycle_length = int(input("Cycle length (days): ").strip()) call_and_display( api.init_menstrual_cycle_setup, period_start_date, period_length, cycle_length, method_name="init_menstrual_cycle_setup", api_call_desc=( "api.init_menstrual_cycle_setup(" f"'{period_start_date}', {period_length}, {cycle_length})" ), ) except Exception as e: print(f"āŒ Error initializing menstrual cycle setup: {e}") def confirm_menstrual_period_start_entry(api: Garmin) -> None: """Confirm a period start date (may confirm a prediction).""" try: period_start_date = input("Period start date (YYYY-MM-DD): ").strip() period_length = int(input("Period length (days): ").strip()) cycle_length = int(input("Cycle length (days): ").strip()) predicted = input("Predicted cycle? [y/N]: ").strip().lower() == "y" call_and_display( api.confirm_menstrual_period_start, period_start_date, period_length, cycle_length, predicted_cycle=predicted, method_name="confirm_menstrual_period_start", api_call_desc=( "api.confirm_menstrual_period_start(" f"'{period_start_date}', {period_length}, {cycle_length})" ), ) except Exception as e: print(f"āŒ Error confirming menstrual period start: {e}") def update_menstrual_settings_entry(api: Garmin) -> None: """PUT menstrual tracking settings.""" try: print( "Paste a JSON object of fields to change. " "Other menstrual settings are kept." ) raw = input("Settings JSON: ").strip() settings = json.loads(raw) call_and_display( api.update_menstrual_settings, settings, method_name="update_menstrual_settings", api_call_desc="api.update_menstrual_settings({...})", ) except Exception as e: print(f"āŒ Error updating menstrual settings: {e}") JETLAG_FLIGHTS_EXAMPLE = ( '[{"originLocation": "Portland, OR, United States", ' '"originTimezone": "-07:00", "originTimestamp": "2027-10-04T15:20:00.00", ' '"destinationLocation": "Melbourne, VIC 3004, Australia", ' '"destinationTimezone": "+11:00", ' '"destinationTimestamp": "2027-10-06T06:45:00.00"}]' ) def _select_jetlag_trip(api: Garmin) -> dict | None: """List jet lag trips and return the one the user picks.""" trips = api.get_jetlag_trips() if not trips: print("ā„¹ļø No jet lag trips found") return None print("\nJet lag trips:") for i, trip in enumerate(trips): print( f" [{i}] {trip.get('startDate')} to {trip.get('endDate')}, " f"{len(trip.get('flights', []))} flight(s) (ID: {trip.get('tripId')})" ) index_input = input( f"\nEnter trip index (0-{len(trips) - 1}, or 'q' to cancel): " ).strip() if index_input.lower() == "q": print("āŒ Cancelled") return None try: index = int(index_input) except ValueError: print("āŒ Invalid index") return None if not 0 <= index < len(trips): print("āŒ Invalid index") return None return trips[index] def add_jetlag_trip_entry(api: Garmin) -> None: """Create a jet lag trip from dates and a pasted JSON list of flights.""" try: start_date = input("Start date (YYYY-MM-DD): ").strip() end_date = input("End date (YYYY-MM-DD): ").strip() print("Paste the flights as a JSON list. Times are local, with no offset.") print(f"Example: {JETLAG_FLIGHTS_EXAMPLE}") flights = json.loads(input("Flights JSON: ").strip()) call_and_display( api.add_jetlag_trip, start_date, end_date, flights, method_name="add_jetlag_trip", api_call_desc=f"api.add_jetlag_trip('{start_date}', '{end_date}', [...])", ) except Exception as e: print(f"āŒ Error adding jet lag trip: {e}") def update_jetlag_trip_entry(api: Garmin) -> None: """Replace the dates and, optionally, the flights of a jet lag trip.""" try: trip = _select_jetlag_trip(api) if trip is None: return trip_id = trip["tripId"] start_date = ( input(f"Start date [{trip['startDate']}]: ").strip() or trip["startDate"] ) end_date = input(f"End date [{trip['endDate']}]: ").strip() or trip["endDate"] print("Paste a JSON list to replace all flights, or press Enter to keep them.") raw = input("Flights JSON: ").strip() flights = json.loads(raw) if raw else trip["flights"] call_and_display( api.update_jetlag_trip, trip_id, start_date, end_date, flights, method_name="update_jetlag_trip", api_call_desc=( f"api.update_jetlag_trip({trip_id}, '{start_date}', '{end_date}', [...])" ), ) except Exception as e: print(f"āŒ Error updating jet lag trip: {e}") def delete_jetlag_trip_entry(api: Garmin) -> None: """Delete a jet lag trip after a y/N confirmation.""" try: trip = _select_jetlag_trip(api) if trip is None: return trip_id = trip["tripId"] confirm = input( f"Delete trip {trip['startDate']} to {trip['endDate']} " f"(ID: {trip_id})? (y/N): " ).strip() if confirm.lower() != "y": print("āŒ Cancelled") return call_and_display( api.delete_jetlag_trip, trip_id, method_name="delete_jetlag_trip", api_call_desc=f"api.delete_jetlag_trip({trip_id})", ) except Exception as e: print(f"āŒ Error deleting jet lag trip: {e}") def set_blood_pressure_data(api: Garmin) -> None: """Set blood pressure (and pulse) data.""" try: print("🩸 Adding blood pressure (and pulse) measurement") print("Enter blood pressure values (press Enter for defaults):") # Get systolic pressure systolic_input = input("Systolic pressure [120]: ").strip() systolic = int(systolic_input) if systolic_input else 120 # Get diastolic pressure diastolic_input = input("Diastolic pressure [80]: ").strip() diastolic = int(diastolic_input) if diastolic_input else 80 # Get pulse (optional - Garmin Connect's own UI allows omitting it) pulse_input = input("Pulse rate (optional, press Enter to omit): ").strip() pulse = int(pulse_input) if pulse_input else None # Get notes (optional) notes = input("Notes (optional): ").strip() or "Added via demo.py" # Validate ranges (must match Garmin.set_blood_pressure's own checks, # so a value the demo accepts never gets rejected by the API call) if not (70 <= systolic <= 260): print("āŒ Invalid systolic pressure (should be between 70-260)") return if not (40 <= diastolic <= 150): print("āŒ Invalid diastolic pressure (should be between 40-150)") return if pulse is not None and not (20 <= pulse <= 250): print("āŒ Invalid pulse rate (should be between 20-250)") return pulse_desc = f"pulse {pulse} bpm" if pulse is not None else "no pulse" print(f"šŸ“Š Recording: {systolic}/{diastolic} mmHg, {pulse_desc}") call_and_display( api.set_blood_pressure, systolic, diastolic, pulse, notes=notes, method_name="set_blood_pressure", api_call_desc=f"api.set_blood_pressure({systolic}, {diastolic}, {pulse}, notes='{notes}')", ) print("āœ… Blood pressure data set successfully!") except ValueError: print("āŒ Invalid input - please enter numeric values") except Exception as e: print(f"āŒ Error setting blood pressure: {e}") def track_gear_usage_data(api: Garmin) -> None: """Calculate total time of use of a piece of gear by going through all activities where said gear has been used.""" try: device_last_used = api.get_device_last_used() user_profile_number = device_last_used.get("userProfileNumber") if user_profile_number: gear_list = api.get_gear(user_profile_number) # call_and_display(api.get_gear, user_profile_number, method_name="get_gear", api_call_desc=f"api.get_gear({user_profile_number})") if gear_list and isinstance(gear_list, list): first_gear = gear_list[0] gear_uuid = first_gear.get("uuid") gear_name = first_gear.get("displayName", "Unknown") print(f"Tracking usage for gear: {gear_name} (UUID: {gear_uuid})") activityList = api.get_gear_activities(gear_uuid) if len(activityList) == 0: print("No activities found for the given gear uuid.") else: print("Found " + str(len(activityList)) + " activities.") D = 0 for a in activityList: print( "Activity: " + a["startTimeLocal"] + (" | " + a["activityName"] if a["activityName"] else "") ) print( " Duration: " + format_timedelta(datetime.timedelta(seconds=a["duration"])) ) D += a["duration"] print("") print( "Total Duration: " + format_timedelta(datetime.timedelta(seconds=D)) ) print("") else: print("No gear found for this user.") else: print("āŒ Could not get user profile number") except Exception as e: print(f"āŒ Error getting gear for track_gear_usage_data: {e}") # --- Interactive helpers for the edit calls (write to the account; each asks first) --- def _pick(items: list, label: str, show) -> Any | None: """Let the user pick one item from a short numbered list (or cancel).""" if not items: print(f"āŒ No {label} found") return None for i, item in enumerate(items, 1): print(f" [{i}] {show(item)}") choice = input(f"Choose a {label} (1-{len(items)}, Enter to cancel): ").strip() if not choice.isdigit() or not 1 <= int(choice) <= len(items): print("Cancelled") return None return items[int(choice) - 1] def update_gear_notes_data(api: Garmin) -> None: """Edit the notes of a piece of gear (gear-service v2).""" try: gear = _pick( api.get_gear_list(0, 50), "gear item", lambda g: ( f"{g.get('name')} ({g.get('brand')} {g.get('model')}) notes={g.get('notes')!r}" ), ) if not gear: return notes = input("New notes (Enter to keep, '-' to clear): ").strip() if not notes: print("Cancelled") return notes = "" if notes == "-" else notes call_and_display( api.update_gear, gear["uuid"], notes=notes, method_name="update_gear", api_call_desc=f"api.update_gear('{gear['uuid']}', notes={notes!r})", ) except Exception as e: print(f"āŒ Error updating gear: {e}") def delete_gear_data(api: Garmin) -> None: """Delete a piece of gear after typing its name to confirm.""" try: gear = _pick( api.get_gear_list(0, 50), "gear item", lambda g: ( f"{g.get('name')} ({g.get('brand')} {g.get('model')}, {g.get('status')})" ), ) if not gear: return if ( input(f"Type the gear name '{gear['name']}' to delete it: ").strip() != gear["name"] ): print("Cancelled") return call_and_display( api.delete_gear, gear["uuid"], method_name="delete_gear", api_call_desc=f"api.delete_gear('{gear['uuid']}')", ) except Exception as e: print(f"āŒ Error deleting gear: {e}") def set_steps_goal_data(api: Garmin) -> None: """Set a manual step goal or return to the automatic one.""" try: current = api.get_steps_goal() print(f"Current goal: {current}") value = input("Manual step goal (Enter for automatic goal): ").strip() steps = int(value) if value else None call_and_display( api.set_steps_goal, steps, method_name="set_steps_goal", api_call_desc=f"api.set_steps_goal({steps})", ) except Exception as e: print(f"āŒ Error setting step goal: {e}") def set_daily_goal_data(api: Garmin) -> None: """Set an intensity-minutes, floors or hydration goal.""" try: goals = api.get_effective_goals() print(f"Effective goals: {goals}") goal = _pick(goals, "goal", lambda g: f"{g['goalType']} = {g['goalValue']}") if not goal: return value = input(f"New value for {goal['goalType']}: ").strip() if not value: print("Cancelled") return call_and_display( api.set_daily_goal, goal["goalType"], float(value), method_name="set_daily_goal", api_call_desc=f"api.set_daily_goal('{goal['goalType']}', {value})", ) except Exception as e: print(f"āŒ Error setting goal: {e}") def calendar_note_data(api: Garmin) -> None: """Add a calendar note for today and optionally delete it again.""" try: name = input("Note title (default: 'Demo note'): ").strip() or "Demo note" content = input("Note content (optional): ").strip() note = api.create_calendar_note(_today(), name, content) _display_single( f"api.create_calendar_note('{_today()}', {name!r}, {content!r})", note ) note_id = note.get("id") if isinstance(note, dict) else None if not note_id: print("āš ļø The response has no note id; delete the note in Garmin Connect") return if input("Delete it again? (y/N): ").strip().lower() == "y": call_and_display( api.delete_calendar_note, note_id, method_name="delete_calendar_note", api_call_desc=f"api.delete_calendar_note({note_id})", ) except Exception as e: print(f"āŒ Error with calendar note: {e}") def update_blood_pressure_note_data(api: Garmin) -> None: """Edit the note of a blood pressure reading from the last 30 days.""" try: data = api.get_blood_pressure(_month_ago(), _today()) readings = [ m for day in (data or {}).get("measurementSummaries", []) for m in day.get("measurements", []) ] reading = _pick( readings, "reading", lambda m: ( f"{m.get('measurementTimestampLocal')} {m.get('systolic')}/{m.get('diastolic')} notes={m.get('notes')!r}" ), ) if not reading: return notes = input("New note: ").strip() call_and_display( api.update_blood_pressure, reading, notes=notes, method_name="update_blood_pressure", api_call_desc=f"api.update_blood_pressure(, notes={notes!r})", ) except Exception as e: print(f"āŒ Error updating blood pressure note: {e}") def set_primary_training_device_data(api: Garmin) -> None: """Choose the primary training device.""" try: device = _pick( api.get_devices(), "device", lambda d: f"{d.get('productDisplayName')} (id {d.get('deviceId')})", ) if not device: return call_and_display( api.set_primary_training_device, device["deviceId"], method_name="set_primary_training_device", api_call_desc=f"api.set_primary_training_device({device['deviceId']})", ) except Exception as e: print(f"āŒ Error setting primary training device: {e}") def update_activity_name_data(api: Garmin) -> None: """Rename the latest activity through the generic update call.""" try: activity = api.get_last_activity() if not activity: print("āŒ No activities found") return print( f"Latest activity: {activity.get('activityName')} ({activity.get('activityId')})" ) name = input("New name (Enter to cancel): ").strip() if not name: print("Cancelled") return call_and_display( api.update_activity, activity["activityId"], {"activityName": name}, method_name="update_activity", api_call_desc=f"api.update_activity({activity['activityId']}, {{'activityName': {name!r}}})", ) except Exception as e: print(f"āŒ Error updating activity: {e}") def execute_api_call(api: Garmin, key: str) -> None: """Execute an API call based on the key.""" if not api: print("API not available") return try: # Map of keys to API methods - this can be extended as needed api_methods = { # User & Profile "get_full_name": lambda: call_and_display( api.get_full_name, method_name="get_full_name", api_call_desc="api.get_full_name()", ), "get_unit_system": lambda: call_and_display( api.get_unit_system, method_name="get_unit_system", api_call_desc="api.get_unit_system()", ), "get_user_profile": lambda: call_and_display( api.get_user_profile, method_name="get_user_profile", api_call_desc="api.get_user_profile()", ), "get_userprofile_settings": lambda: call_and_display( api.get_userprofile_settings, method_name="get_userprofile_settings", api_call_desc="api.get_userprofile_settings()", ), # Daily Health & Activity "get_stats": lambda: call_and_display( api.get_stats, config.today.isoformat(), method_name="get_stats", api_call_desc=f"api.get_stats('{config.today.isoformat()}')", ), "get_user_summary": lambda: call_and_display( api.get_user_summary, config.today.isoformat(), method_name="get_user_summary", api_call_desc=f"api.get_user_summary('{config.today.isoformat()}')", ), "get_stats_and_body": lambda: call_and_display( api.get_stats_and_body, config.today.isoformat(), method_name="get_stats_and_body", api_call_desc=f"api.get_stats_and_body('{config.today.isoformat()}')", ), "get_steps_data": lambda: call_and_display( api.get_steps_data, config.today.isoformat(), method_name="get_steps_data", api_call_desc=f"api.get_steps_data('{config.today.isoformat()}')", ), "get_heart_rates": lambda: call_and_display( api.get_heart_rates, config.today.isoformat(), method_name="get_heart_rates", api_call_desc=f"api.get_heart_rates('{config.today.isoformat()}')", ), "get_rhr_daily": lambda: call_and_display( api.get_rhr_daily, config.week_start.isoformat(), config.today.isoformat(), method_name="get_rhr_daily", api_call_desc=f"api.get_rhr_daily('{config.week_start.isoformat()}', '{config.today.isoformat()}')", ), "get_sleep_daily": lambda: call_and_display( api.get_sleep_daily, config.week_start.isoformat(), config.today.isoformat(), method_name="get_sleep_daily", api_call_desc=f"api.get_sleep_daily('{config.week_start.isoformat()}', '{config.today.isoformat()}')", ), "get_all_day_stress": lambda: call_and_display( api.get_all_day_stress, config.today.isoformat(), method_name="get_all_day_stress", api_call_desc=f"api.get_all_day_stress('{config.today.isoformat()}')", ), "get_calories_daily": lambda: call_and_display( api.get_calories_daily, config.week_start.isoformat(), config.today.isoformat(), method_name="get_calories_daily", api_call_desc=f"api.get_calories_daily('{config.week_start.isoformat()}', '{config.today.isoformat()}')", ), # Advanced Health Metrics "get_running_tolerance": lambda: call_and_display( api.get_running_tolerance, config.week_start.isoformat(), config.today.isoformat(), ), "get_training_readiness": lambda: call_and_display( api.get_training_readiness, config.today.isoformat(), method_name="get_training_readiness", api_call_desc=f"api.get_training_readiness('{config.today.isoformat()}')", ), "get_morning_training_readiness": lambda: call_and_display( api.get_morning_training_readiness, config.today.isoformat(), method_name="get_morning_training_readiness", api_call_desc=f"api.get_morning_training_readiness('{config.today.isoformat()}')", ), "get_training_status": lambda: call_and_display( api.get_training_status, config.today.isoformat(), method_name="get_training_status", api_call_desc=f"api.get_training_status('{config.today.isoformat()}')", ), "get_training_four_week_load_balance": lambda: call_and_display( api.get_training_four_week_load_balance, config.today.isoformat(), method_name="get_training_four_week_load_balance", api_call_desc=f"api.get_training_four_week_load_balance('{config.today.isoformat()}')", ), "get_daily_training_status": lambda: call_and_display( api.get_daily_training_status, config.today.isoformat(), method_name="get_daily_training_status", api_call_desc=f"api.get_daily_training_status('{config.today.isoformat()}')", ), "get_training_load_activities": lambda: call_and_display( api.get_training_load_activities, config.month_start.isoformat(), config.today.isoformat(), method_name="get_training_load_activities", api_call_desc=f"api.get_training_load_activities('{config.month_start.isoformat()}', '{config.today.isoformat()}')", ), "get_respiration_data": lambda: call_and_display( api.get_respiration_data, config.today.isoformat(), method_name="get_respiration_data", api_call_desc=f"api.get_respiration_data('{config.today.isoformat()}')", ), "get_spo2_data": lambda: call_and_display( api.get_spo2_data, config.today.isoformat(), method_name="get_spo2_data", api_call_desc=f"api.get_spo2_data('{config.today.isoformat()}')", ), "get_max_metrics_range": lambda: call_and_display( api.get_max_metrics_range, config.week_start.isoformat(), config.today.isoformat(), method_name="get_max_metrics_range", api_call_desc=f"api.get_max_metrics_range('{config.week_start.isoformat()}', '{config.today.isoformat()}')", ), "get_hrv_data_range": lambda: call_and_display( api.get_hrv_data_range, config.week_start.isoformat(), config.today.isoformat(), method_name="get_hrv_data_range", api_call_desc=f"api.get_hrv_data_range('{config.week_start.isoformat()}', '{config.today.isoformat()}')", ), "get_fitnessage_data": lambda: call_and_display( api.get_fitnessage_data, config.today.isoformat(), method_name="get_fitnessage_data", api_call_desc=f"api.get_fitnessage_data('{config.today.isoformat()}')", ), "get_stress_data": lambda: call_and_display( api.get_stress_data, config.today.isoformat(), method_name="get_stress_data", api_call_desc=f"api.get_stress_data('{config.today.isoformat()}')", ), "get_lactate_threshold": lambda: get_lactate_threshold_data(api), "get_functional_threshold_power_range": lambda: ( get_functional_threshold_power_range_data(api) ), "get_heart_rate_zones": lambda: call_and_display( api.get_heart_rate_zones, method_name="get_heart_rate_zones", api_call_desc="api.get_heart_rate_zones()", ), "get_power_zones": lambda: call_and_display( api.get_power_zones, method_name="get_power_zones", api_call_desc="api.get_power_zones()", ), "get_power_zones_for_sport": lambda: call_and_display( api.get_power_zones_for_sport, "CYCLING", method_name="get_power_zones_for_sport", api_call_desc="api.get_power_zones_for_sport('CYCLING')", ), "get_intensity_minutes_data": lambda: call_and_display( api.get_intensity_minutes_data, config.today.isoformat(), method_name="get_intensity_minutes_data", api_call_desc=f"api.get_intensity_minutes_data('{config.today.isoformat()}')", ), "get_lifestyle_logging_data": lambda: call_and_display( api.get_lifestyle_logging_data, config.today.isoformat(), method_name="get_lifestyle_logging_data", api_call_desc=f"api.get_lifestyle_logging_data('{config.today.isoformat()}')", ), # Historical Data & Trends "get_daily_steps": lambda: call_and_display( api.get_daily_steps, config.week_start.isoformat(), config.today.isoformat(), method_name="get_daily_steps", api_call_desc=f"api.get_daily_steps('{config.week_start.isoformat()}', '{config.today.isoformat()}')", ), "get_body_battery": lambda: call_and_display( api.get_body_battery, config.week_start.isoformat(), config.today.isoformat(), method_name="get_body_battery", api_call_desc=f"api.get_body_battery('{config.week_start.isoformat()}', '{config.today.isoformat()}')", ), "get_floors": lambda: call_and_display( api.get_floors, config.week_start.isoformat(), method_name="get_floors", api_call_desc=f"api.get_floors('{config.week_start.isoformat()}')", ), "get_blood_pressure": lambda: call_and_display( api.get_blood_pressure, config.week_start.isoformat(), config.today.isoformat(), method_name="get_blood_pressure", api_call_desc=f"api.get_blood_pressure('{config.week_start.isoformat()}', '{config.today.isoformat()}')", ), "get_progress_summary_between_dates": lambda: call_and_display( api.get_progress_summary_between_dates, config.week_start.isoformat(), config.today.isoformat(), method_name="get_progress_summary_between_dates", api_call_desc=f"api.get_progress_summary_between_dates('{config.week_start.isoformat()}', '{config.today.isoformat()}')", ), "get_body_battery_events": lambda: call_and_display( api.get_body_battery_events, config.week_start.isoformat(), method_name="get_body_battery_events", api_call_desc=f"api.get_body_battery_events('{config.week_start.isoformat()}')", ), "get_weekly_steps": lambda: call_and_display( api.get_weekly_steps, config.today.isoformat(), 52, method_name="get_weekly_steps", api_call_desc=f"api.get_weekly_steps('{config.today.isoformat()}', 52)", ), "get_weekly_stress": lambda: call_and_display( api.get_weekly_stress, config.today.isoformat(), 52, method_name="get_weekly_stress", api_call_desc=f"api.get_weekly_stress('{config.today.isoformat()}', 52)", ), "get_weekly_intensity_minutes": lambda: call_and_display( api.get_weekly_intensity_minutes, config.week_start.isoformat(), config.today.isoformat(), method_name="get_weekly_intensity_minutes", api_call_desc=f"api.get_weekly_intensity_minutes('{config.week_start.isoformat()}', '{config.today.isoformat()}')", ), # Activities & Workouts "get_activities": lambda: call_and_display( api.get_activities, config.start, config.default_limit, method_name="get_activities", api_call_desc=f"api.get_activities({config.start}, {config.default_limit})", ), "get_activities_filtered": lambda: get_activities_filtered_data(api), "get_next_scheduled_workout": lambda: get_next_scheduled_workout_data(api), "get_last_activity": lambda: call_and_display( api.get_last_activity, method_name="get_last_activity", api_call_desc="api.get_last_activity()", ), "get_activities_fordate": lambda: call_and_display( api.get_activities_fordate, config.today.isoformat(), method_name="get_activities_fordate", api_call_desc=f"api.get_activities_fordate('{config.today.isoformat()}')", ), "get_activity_types": lambda: call_and_display( api.get_activity_types, method_name="get_activity_types", api_call_desc="api.get_activity_types()", ), "get_workouts": lambda: call_and_display( api.get_workouts, method_name="get_workouts", api_call_desc="api.get_workouts()", ), "get_training_plan_by_id": lambda: get_training_plan_by_id_data(api), "get_training_plans": lambda: call_and_display( api.get_training_plans, method_name="get_training_plans", api_call_desc="api.get_training_plans()", ), # Golf "get_golf_summary": lambda: call_and_display( api.get_golf_summary, method_name="get_golf_summary", api_call_desc="api.get_golf_summary()", ), "get_golf_scorecard": lambda: get_golf_scorecard_data(api), "get_golf_shot_data": lambda: get_golf_shot_data_entry(api), "get_golf_club_stats": lambda: call_and_display( api.get_golf_club_stats, method_name="get_golf_club_stats", api_call_desc="api.get_golf_club_stats()", ), "get_golf_user_stats": lambda: call_and_display( api.get_golf_user_stats, method_name="get_golf_user_stats", api_call_desc="api.get_golf_user_stats()", ), "upload_activity": lambda: upload_activity_file(api), "import_activity": lambda: import_activity_file(api), "download_activities": lambda: download_activities_by_date(api), "get_activity_splits": lambda: get_activity_splits_data(api), "get_activity_typed_splits": lambda: get_activity_typed_splits_data(api), "get_activity_split_summaries": lambda: get_activity_split_summaries_data( api ), "get_activity_weather": lambda: get_activity_weather_data(api), "get_activity_hr_in_timezones": lambda: get_activity_hr_timezones_data(api), "get_activity_power_in_timezones": lambda: ( get_activity_power_timezones_data(api) ), "get_cycling_ftp": lambda: get_cycling_ftp_data(api), "get_activity_details": lambda: get_activity_details_data(api), "get_activity_gear": lambda: get_activity_gear_data(api), "get_activity": lambda: get_single_activity_data(api), "get_activity_images": lambda: get_activity_images_data(api), "get_activity_exercise_sets": lambda: get_activity_exercise_sets_data(api), "get_workout_by_id": lambda: get_workout_by_id_data(api), "download_workout": lambda: download_workout_data(api), "upload_workout": lambda: upload_workout_data(api), "upload_running_workout": lambda: upload_running_workout_data(api), "upload_cycling_workout": lambda: upload_cycling_workout_data(api), "upload_swimming_workout": lambda: upload_swimming_workout_data(api), "upload_swimming_css_workout": lambda: upload_swimming_css_workout_data( api ), "upload_strength_workout": lambda: upload_strength_workout_data(api), "upload_timed_strength_workout": lambda: upload_timed_strength_workout_data( api ), "search_exercise_catalog": lambda: search_exercise_catalog_data(api), "get_scheduled_workout_by_id": lambda: get_scheduled_workout_by_id_data( api ), "get_scheduled_workouts": lambda: get_scheduled_workouts(api), "scheduled_workout": lambda: schedule_workout_data(api), "delete_workout": lambda: delete_workout_data(api), "update_workout": lambda: update_workout_data(api), "push_workout_to_device": lambda: push_workout_to_device_data(api), "unschedule_workout": lambda: unschedule_workout_data(api), "count_activities": lambda: call_and_display( api.count_activities, method_name="count_activities", api_call_desc="api.count_activities()", ), # Body Composition & Weight "get_body_composition": lambda: call_and_display( api.get_body_composition, config.today.isoformat(), method_name="get_body_composition", api_call_desc=f"api.get_body_composition('{config.today.isoformat()}')", ), "get_weigh_ins": lambda: call_and_display( api.get_weigh_ins, config.week_start.isoformat(), config.today.isoformat(), method_name="get_weigh_ins", api_call_desc=f"api.get_weigh_ins('{config.week_start.isoformat()}', '{config.today.isoformat()}')", ), "get_daily_weigh_ins": lambda: call_and_display( api.get_daily_weigh_ins, config.today.isoformat(), method_name="get_daily_weigh_ins", api_call_desc=f"api.get_daily_weigh_ins('{config.today.isoformat()}')", ), "add_weigh_in": lambda: add_weigh_in_data(api), "add_body_composition": lambda: add_body_composition_data(api), "delete_weigh_ins": lambda: delete_weigh_ins_data(api), "delete_weigh_in": lambda: delete_weigh_in_data(api), # Goals & Achievements "get_personal_records": lambda: get_personal_records_data(api), "get_earned_badges": lambda: call_and_display( api.get_earned_badges, method_name="get_earned_badges", api_call_desc="api.get_earned_badges()", ), "get_adhoc_challenges": lambda: call_and_display( api.get_adhoc_challenges, config.start, config.default_limit, method_name="get_adhoc_challenges", api_call_desc=f"api.get_adhoc_challenges({config.start}, {config.default_limit})", ), "get_available_badge_challenges": lambda: call_and_display( api.get_available_badge_challenges, config.start_badge, config.default_limit, method_name="get_available_badge_challenges", api_call_desc=f"api.get_available_badge_challenges({config.start_badge}, {config.default_limit})", ), "get_active_goals": lambda: call_and_display( api.get_goals, status="active", start=config.start_badge, limit=config.default_limit, method_name="get_goals", api_call_desc=f"api.get_goals(status='active', start={config.start_badge},limit={config.default_limit})", ), "get_future_goals": lambda: call_and_display( api.get_goals, status="future", start=config.start_badge, limit=config.default_limit, method_name="get_goals", api_call_desc=f"api.get_goals(status='future', start={config.start_badge},limit={config.default_limit})", ), "get_past_goals": lambda: call_and_display( api.get_goals, status="past", start=config.start_badge, limit=config.default_limit, method_name="get_goals", api_call_desc=f"api.get_goals(status='past', start={config.start_badge},limit={config.default_limit})", ), "get_badge_challenges": lambda: call_and_display( api.get_badge_challenges, config.start_badge, config.default_limit, method_name="get_badge_challenges", api_call_desc=f"api.get_badge_challenges({config.start_badge}, {config.default_limit})", ), "get_non_completed_badge_challenges": lambda: call_and_display( api.get_non_completed_badge_challenges, config.start_badge, config.default_limit, method_name="get_non_completed_badge_challenges", api_call_desc=f"api.get_non_completed_badge_challenges({config.start_badge}, {config.default_limit})", ), "get_inprogress_virtual_challenges": lambda: get_virtual_challenges_data( api ), "get_race_predictions": lambda: call_and_display( api.get_race_predictions, method_name="get_race_predictions", api_call_desc="api.get_race_predictions()", ), "get_hill_score": lambda: call_and_display( api.get_hill_score, config.week_start.isoformat(), config.today.isoformat(), method_name="get_hill_score", api_call_desc=f"api.get_hill_score('{config.week_start.isoformat()}', '{config.today.isoformat()}')", ), "get_endurance_score": lambda: call_and_display( api.get_endurance_score, config.week_start.isoformat(), config.today.isoformat(), method_name="get_endurance_score", api_call_desc=f"api.get_endurance_score('{config.week_start.isoformat()}', '{config.today.isoformat()}')", ), "get_available_badges": lambda: call_and_display( api.get_available_badges, method_name="get_available_badges", api_call_desc="api.get_available_badges()", ), "get_in_progress_badges": lambda: call_and_display( api.get_in_progress_badges, method_name="get_in_progress_badges", api_call_desc="api.get_in_progress_badges()", ), # Device & Technical "get_devices": lambda: call_and_display( api.get_devices, method_name="get_devices", api_call_desc="api.get_devices()", ), "get_device_alarms": lambda: call_and_display( api.get_device_alarms, method_name="get_device_alarms", api_call_desc="api.get_device_alarms()", ), "get_solar_data": lambda: get_solar_data(api), "request_reload": lambda: call_and_display( api.request_reload, config.today.isoformat(), method_name="request_reload", api_call_desc=f"api.request_reload('{config.today.isoformat()}')", ), "get_device_settings": lambda: get_device_settings_data(api), "get_device_last_used": lambda: call_and_display( api.get_device_last_used, method_name="get_device_last_used", api_call_desc="api.get_device_last_used()", ), "get_primary_training_device": lambda: call_and_display( api.get_primary_training_device, method_name="get_primary_training_device", api_call_desc="api.get_primary_training_device()", ), # Gear & Equipment "get_gear": lambda: get_gear_data(api), "get_gear_defaults": lambda: get_gear_defaults_data(api), "get_gear_stats": lambda: get_gear_stats_data(api), "get_gear_activities": lambda: get_gear_activities_data(api), "set_gear_default": lambda: set_gear_default_data(api), "track_gear_usage": lambda: track_gear_usage_data(api), "add_and_remove_gear_to_activity": lambda: add_and_remove_gear_to_activity( api ), "create_gear": lambda: create_gear_data(api), # Hydration & Wellness "get_hydration_data": lambda: call_and_display( api.get_hydration_data, config.today.isoformat(), method_name="get_hydration_data", api_call_desc=f"api.get_hydration_data('{config.today.isoformat()}')", ), "get_pregnancy_summary": lambda: call_and_display( api.get_pregnancy_summary, method_name="get_pregnancy_summary", api_call_desc="api.get_pregnancy_summary()", ), "get_all_day_events": lambda: call_and_display( api.get_all_day_events, config.week_start.isoformat(), method_name="get_all_day_events", api_call_desc=f"api.get_all_day_events('{config.week_start.isoformat()}')", ), "add_hydration_data": lambda: add_hydration_data_entry(api), "set_blood_pressure": lambda: set_blood_pressure_data(api), "get_menstrual_data_for_date": lambda: call_and_display( api.get_menstrual_data_for_date, config.today.isoformat(), method_name="get_menstrual_data_for_date", api_call_desc=f"api.get_menstrual_data_for_date('{config.today.isoformat()}')", ), "get_menstrual_calendar_data": lambda: call_and_display( api.get_menstrual_calendar_data, config.week_start.isoformat(), config.today.isoformat(), method_name="get_menstrual_calendar_data", api_call_desc=f"api.get_menstrual_calendar_data('{config.week_start.isoformat()}', '{config.today.isoformat()}')", ), "get_menstrual_last_confirmed": lambda: call_and_display( api.get_menstrual_last_confirmed, config.today.isoformat(), method_name="get_menstrual_last_confirmed", api_call_desc=( f"api.get_menstrual_last_confirmed('{config.today.isoformat()}')" ), ), "get_menstrual_cycle_summary": lambda: call_and_display( api.get_menstrual_cycle_summary, config.today.isoformat(), method_name="get_menstrual_cycle_summary", api_call_desc=( f"api.get_menstrual_cycle_summary('{config.today.isoformat()}')" ), ), "get_menstrual_reports": lambda: call_and_display( api.get_menstrual_reports, config.today.isoformat(), 6, method_name="get_menstrual_reports", api_call_desc=( f"api.get_menstrual_reports('{config.today.isoformat()}', 6)" ), ), "update_menstrual_daily_log": lambda: update_menstrual_daily_log_entry(api), "update_menstrual_calendar": lambda: update_menstrual_calendar_entry(api), "init_menstrual_cycle_setup": lambda: init_menstrual_cycle_setup_entry(api), "confirm_menstrual_period_start": ( lambda: confirm_menstrual_period_start_entry(api) ), "update_menstrual_settings": lambda: update_menstrual_settings_entry(api), # Jet lag "get_jetlag_trips": lambda: call_and_display( api.get_jetlag_trips, method_name="get_jetlag_trips", api_call_desc="api.get_jetlag_trips()", ), "add_jetlag_trip": lambda: add_jetlag_trip_entry(api), "update_jetlag_trip": lambda: update_jetlag_trip_entry(api), "delete_jetlag_trip": lambda: delete_jetlag_trip_entry(api), # Nutrition "get_nutrition_daily_food_log": lambda: call_and_display( api.get_nutrition_daily_food_log, config.today.isoformat(), method_name="get_nutrition_daily_food_log", api_call_desc=f"api.get_nutrition_daily_food_log('{config.today.isoformat()}')", ), "get_nutrition_daily_meals": lambda: call_and_display( api.get_nutrition_daily_meals, config.today.isoformat(), method_name="get_nutrition_daily_meals", api_call_desc=f"api.get_nutrition_daily_meals('{config.today.isoformat()}')", ), "get_nutrition_daily_settings": lambda: call_and_display( api.get_nutrition_daily_settings, config.today.isoformat(), method_name="get_nutrition_daily_settings", api_call_desc=f"api.get_nutrition_daily_settings('{config.today.isoformat()}')", ), # Blood Pressure Management "delete_blood_pressure": lambda: delete_blood_pressure_data(api), # Activity Management "set_activity_name": lambda: set_activity_name_data(api), "set_activity_type": lambda: set_activity_type_data(api), "set_activity_description": lambda: set_activity_description_data(api), "set_activity_exercise_sets": lambda: set_activity_exercise_sets_data(api), "create_manual_activity": lambda: create_manual_activity_data(api), "delete_activity": lambda: delete_activity_data(api), "get_activities_by_date": lambda: call_and_display( api.get_activities_by_date, config.today.isoformat(), config.today.isoformat(), method_name="get_activities_by_date", api_call_desc=f"api.get_activities_by_date('{config.today.isoformat()}', '{config.today.isoformat()}')", ), # System & Export "create_health_report": lambda: DataExporter.create_health_report(api), "remove_tokens": remove_stored_tokens, "disconnect": lambda: disconnect_api(api), "download_health_snapshot": lambda: download_health_snapshot_file(api), # GraphQL Queries "query_garmin_graphql": lambda: query_garmin_graphql_data(api), # Edit calls (interactive) "update_gear_notes": lambda: update_gear_notes_data(api), "delete_gear": lambda: delete_gear_data(api), "set_steps_goal": lambda: set_steps_goal_data(api), "set_daily_goal": lambda: set_daily_goal_data(api), "calendar_note": lambda: calendar_note_data(api), "update_blood_pressure": lambda: update_blood_pressure_note_data(api), "set_primary_training_device": lambda: set_primary_training_device_data( api ), "update_activity": lambda: update_activity_name_data(api), # Endpoints the Garmin Connect web app uses, see docs/API_ENDPOINTS.md "get_max_metrics_latest": _web(api, "get_max_metrics_latest"), "get_training_readiness_range": _web( api, "get_training_readiness_range", lambda: (_week_ago(), _today()) ), "get_weekly_training_status": _web( api, "get_weekly_training_status", lambda: (_month_ago(), _today()) ), "get_heat_altitude_acclimation": _web(api, "get_heat_altitude_acclimation"), "get_heat_altitude_acclimation_range": _web( api, "get_heat_altitude_acclimation_range", lambda: (_week_ago(), _today()), ), "get_cycling_ability": _web(api, "get_cycling_ability"), "get_cycling_ability_range": _web( api, "get_cycling_ability_range", lambda: (_month_ago(), _today()) ), "get_running_economy": _web(api, "get_running_economy"), "get_stamina_curve": _web(api, "get_stamina_curve"), "get_power_curve": _web( api, "get_power_curve", lambda: (_month_ago(), _today()) ), "get_critical_swim_speed": _web(api, "get_critical_swim_speed"), "get_heart_rate_zones_v2": _web(api, "get_heart_rate_zones_v2"), "get_biometric_stats": _web( api, "get_biometric_stats", lambda: (_week_ago(), _today()) ), "get_power_to_weight_range": _web( api, "get_power_to_weight_range", lambda: (_month_ago(), _today()) ), "get_current_biometrics": _web(api, "get_current_biometrics"), "get_fitness_age_details": _web(api, "get_fitness_age_details"), "get_fitness_age_daily": _web( api, "get_fitness_age_daily", lambda: (_week_ago(), _today()) ), "get_fitness_age_weekly": _web( api, "get_fitness_age_weekly", kwargs_fn=lambda: {"weeks": 12} ), "get_personal_record_candidates": _web( api, "get_personal_record_candidates" ), "get_personal_record_types": _web(api, "get_personal_record_types"), "get_available_metrics": _web( api, "get_available_metrics", lambda: (_month_ago(), _today()) ), "get_one_rep_max": _web(api, "get_one_rep_max"), "get_glucose_data": _web(api, "get_glucose_data", lambda: (_today(),)), "get_daily_stats": _web( api, "get_daily_stats", lambda: (_week_ago(), _today(), "STEPS") ), "get_daily_heart_rate_stats": _web( api, "get_daily_heart_rate_stats", lambda: (_week_ago(), _today()) ), "get_weekly_heart_rate_stats": _web( api, "get_weekly_heart_rate_stats", kwargs_fn=lambda: {"weeks": 12} ), "get_daily_stress_stats": _web( api, "get_daily_stress_stats", lambda: (_week_ago(), _today()) ), "get_daily_body_battery_stats": _web( api, "get_daily_body_battery_stats", lambda: (_week_ago(), _today()) ), "get_daily_intensity_minutes_stats": _web( api, "get_daily_intensity_minutes_stats", lambda: (_week_ago(), _today()), ), "get_daily_respiration_stats": _web( api, "get_daily_respiration_stats", lambda: (_week_ago(), _today()) ), "get_daily_floors_stats": _web( api, "get_daily_floors_stats", lambda: (_week_ago(), _today()) ), "get_weekly_calories_stats": _web( api, "get_weekly_calories_stats", kwargs_fn=lambda: {"weeks": 12} ), "get_monthly_steps": _web( api, "get_monthly_steps", kwargs_fn=lambda: {"months": 6} ), "get_stats_averages": _web( api, "get_stats_averages", lambda: (_week_ago(), _today()) ), "get_lifetime_totals": _web(api, "get_lifetime_totals"), "get_daily_summaries": _web( api, "get_daily_summaries", lambda: (_week_ago(), _today()) ), "get_week_average_resting_hr": _web(api, "get_week_average_resting_hr"), "get_hydration_all_data": _web(api, "get_hydration_all_data"), "get_spo2_acclimation_data": _web(api, "get_spo2_acclimation_data"), "get_daily_movement": _web(api, "get_daily_movement"), "get_steps_goal": _web(api, "get_steps_goal"), "get_sync_timestamp": _web(api, "get_sync_timestamp"), "get_hourly_intensity_minutes": _web( api, "get_hourly_intensity_minutes", kwargs_fn=lambda: {"days": 1} ), "get_daily_sleep": _web(api, "get_daily_sleep"), "get_naps": _web(api, "get_naps"), "get_sleep_stats_weekly": _web( api, "get_sleep_stats_weekly", kwargs_fn=lambda: {"weeks": 12} ), "get_sleep_stats_overall": _web( api, "get_sleep_stats_overall", lambda: (_month_ago(), _today()) ), "get_health_snapshots_range": _web( api, "get_health_snapshots_range", lambda: (_month_ago(), _today()) ), "get_nutrition_status": _web(api, "get_nutrition_status"), "get_calorie_summary": _web( api, "get_calorie_summary", lambda: (_week_ago(), _today()) ), "get_latest_weight": _web(api, "get_latest_weight"), "get_first_weight": _web(api, "get_first_weight"), "get_daily_last_weight": _web( api, "get_daily_last_weight", lambda: (_month_ago(), _today()) ), "get_weekly_weight": _web(api, "get_weekly_weight"), "get_blood_pressure_day": _web(api, "get_blood_pressure_day"), "get_ecg_daily": _web( api, "get_ecg_daily", lambda: (_month_ago(), _today()) ), "get_ecg_list": _web(api, "get_ecg_list"), "get_effective_goals": _web(api, "get_effective_goals"), "get_scheduled_workouts_by_period": _web( api, "get_scheduled_workouts_by_period", lambda: (_today(), (config.today + timedelta(days=60)).isoformat()), ), "get_workout_count": _web(api, "get_workout_count"), "get_workout_sport_types": _web(api, "get_workout_sport_types"), "get_workout_types": _web(api, "get_workout_types"), "get_strength_benchmarks": _web(api, "get_strength_benchmarks"), "get_active_training_plans": _web(api, "get_active_training_plans"), "search_training_plans": _web( api, "search_training_plans", lambda: (1, 10) ), "get_calendar_year": _web( api, "get_calendar_year", lambda: (config.today.year,) ), "get_calendar_week": _web(api, "get_calendar_week"), "get_calendar_events": _web( api, "get_calendar_events", lambda: (f"{config.today.year}-01-01", f"{config.today.year}-12-31"), ), "get_upcoming_events": _web(api, "get_upcoming_events"), "get_primary_event": _web(api, "get_primary_event"), "get_courses": _web(api, "get_courses"), "get_course_favorites": _web(api, "get_course_favorites"), "get_pace_bands": _web(api, "get_pace_bands"), "convert_activity_to_course": _web( api, "convert_activity_to_course", lambda: (_latest_activity_id(api),) ), "get_user_goals": _web(api, "get_user_goals"), "get_all_devices": _web(api, "get_all_devices"), "get_historical_devices": _web(api, "get_historical_devices"), "get_active_devices": _web(api, "get_active_devices"), "get_sensors": _web(api, "get_sensors"), "get_device_messages": _web(api, "get_device_messages"), "get_usage_indicators": _web(api, "get_usage_indicators"), "get_personal_information": _web(api, "get_personal_information"), "get_user_profile_base": _web(api, "get_user_profile_base"), "get_privacy_settings": _web(api, "get_privacy_settings"), "get_jetlag_status": _web(api, "get_jetlag_status"), "get_gear_list": _web(api, "get_gear_list"), "get_gear_types": _web(api, "get_gear_types"), "get_badge_attributes": _web(api, "get_badge_attributes"), "get_latest_earned_badges": _web(api, "get_latest_earned_badges"), "get_available_virtual_challenges": _web( api, "get_available_virtual_challenges", lambda: (1, 10) ), "search_activities": _web( api, "search_activities", lambda: (0, 10), lambda: { "activityType": "walking", "startDate": _week_ago(), "endDate": _today(), }, ), "get_fastest_splits": _web( api, "get_fastest_splits", lambda: (f"{config.today.year}-01-01", _today(), "running", 5), ), "get_favorite_activities": _web(api, "get_favorite_activities"), "get_activity_laps": _web( api, "get_activity_laps", lambda: (_latest_activity_id(api),) ), "get_activity_map_details": _web( api, "get_activity_map_details", lambda: (_latest_activity_id(api),) ), "get_adjacent_activities": _web( api, "get_adjacent_activities", lambda: (_latest_activity_id(api),) ), "get_activity_event_types": _web(api, "get_activity_event_types"), "get_activity_gear_v2": _web( api, "get_activity_gear_v2", lambda: (_latest_activity_id(api),) ), "get_activity_segments": _web( api, "get_activity_segments", lambda: (_latest_activity_id(api),) ), "get_personal_records_for_activity": _web( api, "get_personal_records_for_activity", lambda: (_latest_activity_id(api),), ), } if key in api_methods: print(f"\nšŸ”„ Executing: {key}") api_methods[key]() else: print(f"āŒ API method '{key}' not implemented yet. You can add it later!") except Exception as e: print(f"āŒ Error executing {key}: {e}") def remove_stored_tokens(): """Remove stored login tokens.""" try: token_file = token_file_path(config.tokenstore) if not token_file.exists(): print("ā„¹ļø No stored login tokens found") return Garmin().logout(config.tokenstore) print("āœ… Stored login token file removed") except Exception as e: print(f"āŒ Error removing stored login tokens: {e}") def disconnect_api(api: Garmin): """Disconnect from Garmin Connect.""" api.logout() print("āœ… Disconnected from Garmin Connect") def download_health_snapshot_file(api: Garmin): """Download today's Health Snapshot ZIP and save it to the export directory.""" requested_date = config.today.isoformat() try: content = api.download_health_snapshot(requested_date) if not content: print("āŒ No Health Snapshot content available for this date") return safe_date = _safe_filename_component(requested_date) filepath = config.export_dir / f"{safe_date}_HEALTH_SNAPSHOT.zip" with _open_private(filepath, "wb") as f: f.write(content) print(f"āœ… Health Snapshot saved to: {filepath}") except Exception as e: print(f"āŒ Error downloading Health Snapshot: {e}") def init_api(email: str | None = None, password: str | None = None) -> Garmin | None: """Initialize Garmin API with smart error handling and recovery.""" # First try to login with stored tokens try: print(f"Attempting to login using stored tokens from: {config.tokenstore}") garmin = Garmin() garmin.login(config.tokenstore) print("Successfully logged in using stored tokens!") return garmin except GarminConnectTooManyRequestsError as err: print(f"\nāŒ {err}") sys.exit(1) except ( FileNotFoundError, GarminConnectAuthenticationError, GarminConnectConnectionError, ): print("No valid tokens found. Requesting fresh login credentials.") # Loop for credential entry with retry on auth failure while True: try: # Get credentials if not provided if not email or not password: email = input("Email address: ").strip() password = getpass("Password: ") print("Logging in with credentials...") garmin = Garmin( email=email, password=password, is_cn=False, return_on_mfa=True ) # Don't keep the plaintext password in local scope longer than needed. password = None result1, result2 = garmin.login() if result1 == "needs_mfa": print("Multi-factor authentication required") mfa_code = get_mfa() print("šŸ”„ Submitting MFA code...") try: garmin.resume_login(result2, mfa_code) print("āœ… MFA authentication successful!") except GarminConnectTooManyRequestsError: print("āŒ Too many MFA attempts") print("šŸ’” Please wait 30 minutes before trying again") sys.exit(1) except GarminConnectAuthenticationError as mfa_error: # Handle specific errors from MFA error_str = str(mfa_error) print(f"šŸ” Debug: MFA error details: {error_str}") if "401" in error_str or "403" in error_str: print("āŒ Invalid MFA code") print("šŸ’” Please verify your MFA code and try again") continue # Other HTTP errors - don't retry print(f"āŒ MFA authentication failed: {mfa_error}") sys.exit(1) # Save tokens for future use garmin.client.dump(config.tokenstore) print(f"Login successful! Tokens saved to: {config.tokenstore}") return garmin except GarminConnectTooManyRequestsError as err: print(f"\nāŒ {err}") sys.exit(1) except GarminConnectAuthenticationError as err: print(f"\nāŒ {err}") print("šŸ’” Please check your username and password and try again") # Clear the provided credentials to force re-entry email = None password = None continue except ( FileNotFoundError, GarminConnectConnectionError, requests.exceptions.HTTPError, ) as err: print(f"āŒ Connection error: {err}") print("šŸ’” Please check your internet connection and try again") return None except KeyboardInterrupt: print("\nLogin cancelled by user") return None def main(): """Main program loop with funny health status in menu prompt.""" # Display export directory information on startup print(f"šŸ“ Exported data will be saved to the directory: '{config.export_dir}'") print("šŸ“„ All API responses are written to: 'response.json'") api_instance = init_api(config.email, config.password) # Lets config.today follow the Garmin profile timezone instead of the host. config.api = api_instance current_category = None while True: try: if api_instance: # Add health status in menu prompt try: summary = api_instance.get_user_summary(config.today.isoformat()) hydration_data = None with suppress(Exception): hydration_data = api_instance.get_hydration_data( config.today.isoformat() ) if summary: steps = summary.get("totalSteps") or 0 calories = summary.get("totalKilocalories") or 0 # Build stats string with hydration if available stats_parts = [f"{steps:,} steps", f"{calories} kcal"] if hydration_data and hydration_data.get("valueInML"): hydration_ml = int(hydration_data.get("valueInML", 0)) hydration_cups = round(hydration_ml / 240, 1) hydration_goal = hydration_data.get("goalInML", 0) if hydration_goal > 0: hydration_percent = round( (hydration_ml / hydration_goal) * 100 ) stats_parts.append( f"{hydration_ml}ml water ({hydration_percent}% of goal)" ) else: stats_parts.append( f"{hydration_ml}ml water ({hydration_cups} cups)" ) stats_string = " | ".join(stats_parts) print(f"\nšŸ“Š Your Stats Today: {stats_string}") if steps < 5000: print("🐌 Time to get those legs moving!") elif steps > 15000: print("šŸƒā€ā™‚ļø You're crushing it today!") else: print("šŸ‘ Nice progress! Keep it up!") except Exception as e: print( f"Unable to fetch stats for display: {e}" ) # Silently skip if stats can't be fetched # Display appropriate menu if current_category is None: print_main_menu() option = safe_readkey() # Handle main menu options if option == "q": print( "Be active, generate some data to play with next time ;-) Bye!" ) break if option in menu_categories: current_category = option else: print( f"āŒ Invalid selection. Use {', '.join(menu_categories.keys())} for categories or 'q' to quit" ) else: # In a category - show category menu print_category_menu(current_category) option = safe_readkey() # Handle category menu options. Validity is decided solely by # membership in the current category's own options dict — # no separate hardcoded character whitelist to keep in sync # whenever a new option key (e.g. an uppercase letter) is # added to menu_categories. if option == "q": current_category = None # Back to main menu else: try: category_data = menu_categories[current_category] category_options = category_data["options"] if option in category_options: api_key = category_options[option]["key"] execute_api_call(api_instance, api_key) else: valid_keys = ", ".join(category_options.keys()) print( f"āŒ Invalid option selection. Valid options: {valid_keys}" ) except Exception as e: print(f"āŒ Error processing option {option}: {e}") except KeyboardInterrupt: print("\nInterrupted by user. Press q to quit.") except Exception as e: print(f"Unexpected error: {e}") if __name__ == "__main__": main()