Documentation
¶
Overview ¶
Package garminconnect is a Go port of python-garminconnect, an unofficial client for the Garmin Connect API.
Index ¶
- Variables
- func As[T any](raw json.RawMessage, err error) (T, error)
- func PaceToMPS(minutes, seconds int, units string) float64
- func ParseActivityDetailMetrics(details json.RawMessage) ([]map[string]any, error)
- func SpeedToMPS(speed float64, units string) float64
- func StatusCode(err error) int
- func TokenFilePath(path string) (string, error)
- type ActivityDownloadFormat
- type BodyComposition
- type Client
- func (c *Client) Dump(path string) error
- func (c *Client) Dumps() string
- func (c *Client) IsAuthenticated() bool
- func (c *Client) Load(path string) error
- func (c *Client) Loads(s string) error
- func (c *Client) Login(ctx context.Context, email, password string, promptMFA func() (string, error), ...) (needsMFA bool, err error)
- func (c *Client) Request(ctx context.Context, method, path string, opts *RequestOptions) ([]byte, error)
- func (c *Client) ResumeLogin(ctx context.Context, code string) error
- type DailyCalories
- type DailyValue
- type EndCondition
- type Error
- type ExecutableStep
- func CooldownStep(durationSecs float64, order int) *ExecutableStep
- func DistanceIntervalStep(distanceMeters float64, order int, primary, secondary *Target) (*ExecutableStep, error)
- func IntervalStep(durationSecs float64, order int, primary, secondary *Target) (*ExecutableStep, error)
- func RecoveryStep(durationSecs float64, order int) *ExecutableStep
- func StrengthExerciseStep(category string, order, reps int, exerciseName string, weightKG *float64) *ExecutableStep
- func StrengthRestStep(durationSecs float64, order int) *ExecutableStep
- func WarmupStep(durationSecs float64, order int) *ExecutableStep
- type Exercise
- type Garmin
- func (g *Garmin) AddBodyComposition(ctx context.Context, ts time.Time, bc BodyComposition) (json.RawMessage, error)
- func (g *Garmin) AddGearToActivity(ctx context.Context, gearUUID string, activityID int64) (json.RawMessage, error)
- func (g *Garmin) AddHydrationData(ctx context.Context, valueML float64, ts time.Time, cdate string) (json.RawMessage, error)
- func (g *Garmin) AddJetlagTrip(ctx context.Context, start, end string, flights []JetlagFlight) (json.RawMessage, error)
- func (g *Garmin) AddWeighIn(ctx context.Context, weight float64, unit string, ts time.Time) (json.RawMessage, error)
- func (g *Garmin) AddWeighInWithTimestamps(ctx context.Context, weight float64, unit string, local, gmt time.Time) (json.RawMessage, error)
- func (g *Garmin) ConfirmMenstrualPeriodStart(ctx context.Context, periodStart string, periodLength, cycleLength int, ...) (json.RawMessage, error)
- func (g *Garmin) ConnectAPI(ctx context.Context, path string, params url.Values) (json.RawMessage, error)
- func (g *Garmin) CountActivities(ctx context.Context) (int64, error)
- func (g *Garmin) CreateGear(ctx context.Context, s GearSpec) (json.RawMessage, error)
- func (g *Garmin) CreateManualActivity(ctx context.Context, start, timeZone, typeKey string, distanceKM float64, ...) (json.RawMessage, error)
- func (g *Garmin) CreateManualActivityFromJSON(ctx context.Context, payload any) (json.RawMessage, error)
- func (g *Garmin) DeleteActivity(ctx context.Context, id int64) (json.RawMessage, error)
- func (g *Garmin) DeleteBloodPressure(ctx context.Context, version int64, cdate string) (json.RawMessage, error)
- func (g *Garmin) DeleteJetlagTrip(ctx context.Context, tripID int64) (json.RawMessage, error)
- func (g *Garmin) DeleteWeighIn(ctx context.Context, weightPK int64, cdate string) (json.RawMessage, error)
- func (g *Garmin) DeleteWeighIns(ctx context.Context, cdate string, deleteAll bool) (int, error)
- func (g *Garmin) DeleteWorkout(ctx context.Context, id int64) (json.RawMessage, error)
- func (g *Garmin) Download(ctx context.Context, path string) ([]byte, error)
- func (g *Garmin) DownloadActivity(ctx context.Context, id int64, format ActivityDownloadFormat) ([]byte, error)
- func (g *Garmin) DownloadHealthSnapshot(ctx context.Context, date string) ([]byte, error)
- func (g *Garmin) DownloadWorkout(ctx context.Context, id int64) ([]byte, error)
- func (g *Garmin) GetActivities(ctx context.Context, start, limit int, activityType, subType string) (json.RawMessage, error)
- func (g *Garmin) GetActivitiesByDate(ctx context.Context, startdate, enddate, activityType, sortOrder string) (json.RawMessage, error)
- func (g *Garmin) GetActivitiesForDate(ctx context.Context, date string) (json.RawMessage, error)
- func (g *Garmin) GetActivity(ctx context.Context, id int64) (json.RawMessage, error)
- func (g *Garmin) GetActivityDetails(ctx context.Context, id int64, maxChart, maxPoly int) (json.RawMessage, error)
- func (g *Garmin) GetActivityExerciseSets(ctx context.Context, id int64) (json.RawMessage, error)
- func (g *Garmin) GetActivityGear(ctx context.Context, activityID int64) (json.RawMessage, error)
- func (g *Garmin) GetActivityHRInTimezones(ctx context.Context, id int64) (json.RawMessage, error)
- func (g *Garmin) GetActivityImages(ctx context.Context, id int64) (json.RawMessage, error)
- func (g *Garmin) GetActivityPowerInTimezones(ctx context.Context, id int64) (json.RawMessage, error)
- func (g *Garmin) GetActivitySplitSummaries(ctx context.Context, id int64) (json.RawMessage, error)
- func (g *Garmin) GetActivitySplits(ctx context.Context, id int64) (json.RawMessage, error)
- func (g *Garmin) GetActivityTypedSplits(ctx context.Context, id int64) (json.RawMessage, error)
- func (g *Garmin) GetActivityTypes(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetActivityWeather(ctx context.Context, id int64) (json.RawMessage, error)
- func (g *Garmin) GetAdaptiveTrainingPlanByID(ctx context.Context, planID int64) (json.RawMessage, error)
- func (g *Garmin) GetAdhocChallenges(ctx context.Context, start, limit int) (json.RawMessage, error)
- func (g *Garmin) GetAllDayEvents(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetAllDayStress(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetAvailableBadgeChallenges(ctx context.Context, start, limit int) (json.RawMessage, error)
- func (g *Garmin) GetAvailableBadges(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetBadgeChallenges(ctx context.Context, start, limit int) (json.RawMessage, error)
- func (g *Garmin) GetBloodPressure(ctx context.Context, startdate, enddate string) (json.RawMessage, error)
- func (g *Garmin) GetBodyBattery(ctx context.Context, startdate, enddate string) (json.RawMessage, error)
- func (g *Garmin) GetBodyBatteryEvents(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetBodyComposition(ctx context.Context, startdate, enddate string) (json.RawMessage, error)
- func (g *Garmin) GetCaloriesDaily(ctx context.Context, start, end string) ([]DailyCalories, error)
- func (g *Garmin) GetCyclingFTP(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetDailySteps(ctx context.Context, start, end string) (json.RawMessage, error)
- func (g *Garmin) GetDailyTrainingStatus(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetDailyWeighIns(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetDeviceAlarms(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetDeviceLastUsed(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetDeviceSettings(ctx context.Context, deviceID int64) (json.RawMessage, error)
- func (g *Garmin) GetDeviceSolarData(ctx context.Context, deviceID int64, startdate, enddate string) (json.RawMessage, error)
- func (g *Garmin) GetDevices(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetEarnedBadges(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetEnduranceScore(ctx context.Context, startdate, enddate string) (json.RawMessage, error)
- func (g *Garmin) GetFitnessAgeData(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetFloors(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetFunctionalThresholdPowerRange(ctx context.Context, start, end, sport, aggregation string) (json.RawMessage, error)
- func (g *Garmin) GetGear(ctx context.Context, userProfileNumber int64) (json.RawMessage, error)
- func (g *Garmin) GetGearActivities(ctx context.Context, gearUUID string, limit int) (json.RawMessage, error)
- func (g *Garmin) GetGearDefaults(ctx context.Context, userProfileNumber int64) (json.RawMessage, error)
- func (g *Garmin) GetGearStats(ctx context.Context, gearUUID string) (json.RawMessage, error)
- func (g *Garmin) GetGoals(ctx context.Context, status string, start, limit int) (json.RawMessage, error)
- func (g *Garmin) GetGolfClubStats(ctx context.Context, limit int) (json.RawMessage, error)
- func (g *Garmin) GetGolfScorecard(ctx context.Context, scorecardID int64) (json.RawMessage, error)
- func (g *Garmin) GetGolfShotData(ctx context.Context, scorecardID int64, holes string) (json.RawMessage, error)
- func (g *Garmin) GetGolfSummary(ctx context.Context, start, limit int) (json.RawMessage, error)
- func (g *Garmin) GetGolfUserStats(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetHRVData(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetHRVDataRange(ctx context.Context, start, end string) (json.RawMessage, error)
- func (g *Garmin) GetHeartRateZones(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetHeartRates(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetHillScore(ctx context.Context, startdate, enddate string) (json.RawMessage, error)
- func (g *Garmin) GetHydrationData(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetInProgressBadges(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetInProgressVirtualChallenges(ctx context.Context, start, limit int) (json.RawMessage, error)
- func (g *Garmin) GetIntensityMinutesData(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetJetlagTrips(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetLactateThreshold(ctx context.Context, latest bool, start, end, aggregation string) (json.RawMessage, error)
- func (g *Garmin) GetLastActivity(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetLifestyleLoggingData(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetMaxMetrics(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetMaxMetricsRange(ctx context.Context, start, end string) (json.RawMessage, error)
- func (g *Garmin) GetMenstrualCalendarData(ctx context.Context, startdate, enddate string) (json.RawMessage, error)
- func (g *Garmin) GetMenstrualCycleSummary(ctx context.Context, date string) (json.RawMessage, error)
- func (g *Garmin) GetMenstrualDataForDate(ctx context.Context, date string) (json.RawMessage, error)
- func (g *Garmin) GetMenstrualLastConfirmed(ctx context.Context, date string) (json.RawMessage, error)
- func (g *Garmin) GetMenstrualReports(ctx context.Context, date string, cycles int, next bool, ...) (json.RawMessage, error)
- func (g *Garmin) GetMorningTrainingReadiness(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetNextScheduledWorkout(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetNonCompletedBadgeChallenges(ctx context.Context, start, limit int) (json.RawMessage, error)
- func (g *Garmin) GetNutritionDailyFoodLog(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetNutritionDailyMeals(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetNutritionDailySettings(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetPersonalRecord(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetPowerZones(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetPowerZonesForSport(ctx context.Context, sport string) (json.RawMessage, error)
- func (g *Garmin) GetPregnancySummary(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetPrimaryTrainingDevice(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetProgressSummaryBetweenDates(ctx context.Context, startdate, enddate, metric string, groupByActivities bool) (json.RawMessage, error)
- func (g *Garmin) GetRHRDaily(ctx context.Context, start, end string) ([]DailyValue, error)
- func (g *Garmin) GetRHRDay(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetRacePredictions(ctx context.Context, startdate, enddate, predType string) (json.RawMessage, error)
- func (g *Garmin) GetRespirationData(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetRunningTolerance(ctx context.Context, startdate, enddate, aggregation string) (json.RawMessage, error)
- func (g *Garmin) GetScheduledWorkoutByID(ctx context.Context, id int64) (json.RawMessage, error)
- func (g *Garmin) GetScheduledWorkouts(ctx context.Context, year, month int) (json.RawMessage, error)
- func (g *Garmin) GetSleepDaily(ctx context.Context, start, end string) (json.RawMessage, error)
- func (g *Garmin) GetSleepData(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetSpo2Data(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetStats(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetStatsAndBody(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetStepsData(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetStressData(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetTrainingFourWeekLoadBalance(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetTrainingLoadActivities(ctx context.Context, startdate, enddate string, metrics []string, ...) (json.RawMessage, error)
- func (g *Garmin) GetTrainingPlanByID(ctx context.Context, planID int64) (json.RawMessage, error)
- func (g *Garmin) GetTrainingPlans(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetTrainingReadiness(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetTrainingStatus(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetUserProfile(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetUserSummary(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) GetUserprofileSettings(ctx context.Context) (json.RawMessage, error)
- func (g *Garmin) GetWeeklyIntensityMinutes(ctx context.Context, start, end string) (json.RawMessage, error)
- func (g *Garmin) GetWeeklySteps(ctx context.Context, end string, weeks int) (json.RawMessage, error)
- func (g *Garmin) GetWeeklyStress(ctx context.Context, end string, weeks int) (json.RawMessage, error)
- func (g *Garmin) GetWeighIns(ctx context.Context, startdate, enddate string) (json.RawMessage, error)
- func (g *Garmin) GetWorkoutByID(ctx context.Context, id int64) (json.RawMessage, error)
- func (g *Garmin) GetWorkouts(ctx context.Context, start, limit int) (json.RawMessage, error)
- func (g *Garmin) ImportActivity(ctx context.Context, path string) (json.RawMessage, error)
- func (g *Garmin) InitMenstrualCycleSetup(ctx context.Context, periodStart string, periodLength, cycleLength int) (json.RawMessage, error)
- func (g *Garmin) Login(ctx context.Context, tokenstore string) (needsMFA bool, err error)
- func (g *Garmin) Logout(tokenstore string) error
- func (g *Garmin) PushWorkoutToDevice(ctx context.Context, workoutID, deviceID int64) (json.RawMessage, error)
- func (g *Garmin) QueryGarminGraphQL(ctx context.Context, query any) (json.RawMessage, error)
- func (g *Garmin) RemoveGearFromActivity(ctx context.Context, gearUUID string, activityID int64) (json.RawMessage, error)
- func (g *Garmin) RequestReload(ctx context.Context, cdate string) (json.RawMessage, error)
- func (g *Garmin) ResumeLogin(ctx context.Context, code string) error
- func (g *Garmin) ScheduleWorkout(ctx context.Context, workoutID int64, date string) (json.RawMessage, error)
- func (g *Garmin) SetActivityDescription(ctx context.Context, id int64, description string) (json.RawMessage, error)
- func (g *Garmin) SetActivityExerciseSets(ctx context.Context, id int64, payload any) (json.RawMessage, error)
- func (g *Garmin) SetActivityName(ctx context.Context, id int64, title string) (json.RawMessage, error)
- func (g *Garmin) SetActivityType(ctx context.Context, id int64, typeID int, typeKey string, parentTypeID int) (json.RawMessage, error)
- func (g *Garmin) SetBloodPressure(ctx context.Context, systolic, diastolic, pulse int, ts time.Time, ...) (json.RawMessage, error)
- func (g *Garmin) SetGearDefault(ctx context.Context, activityType, gearUUID string, defaultGear bool) (json.RawMessage, error)
- func (g *Garmin) UnscheduleWorkout(ctx context.Context, scheduledWorkoutID int64) (json.RawMessage, error)
- func (g *Garmin) UpdateJetlagTrip(ctx context.Context, tripID int64, start, end string, flights []JetlagFlight) (json.RawMessage, error)
- func (g *Garmin) UpdateMenstrualCalendar(ctx context.Context, startdate, enddate string, cycleDates [][]string, ...) (json.RawMessage, error)
- func (g *Garmin) UpdateMenstrualDailyLog(ctx context.Context, date string, l MenstrualDailyLog) (json.RawMessage, error)
- func (g *Garmin) UpdateMenstrualSettings(ctx context.Context, settings map[string]any, userSettingsID int64) (json.RawMessage, error)
- func (g *Garmin) UpdateWorkout(ctx context.Context, id int64, workout any) (json.RawMessage, error)
- func (g *Garmin) UploadActivity(ctx context.Context, path string) (json.RawMessage, error)
- func (g *Garmin) UploadWorkout(ctx context.Context, workout any) (json.RawMessage, error)
- type GearSpec
- type JetlagFlight
- type MenstrualDailyLog
- type Option
- func WithCN() Option
- func WithLogger(l *slog.Logger) Option
- func WithPromptMFA(fn func() (string, error)) Option
- func WithRetry(attempts int, minWait, maxWait time.Duration) Option
- func WithReturnOnMFA() Option
- func WithTokenSaver(fn func(tokenJSON string)) Option
- func WithVerifyLogin(v bool) Option
- type RepeatGroup
- type RequestOptions
- type SportType
- type Step
- type StepType
- type Target
- func CadenceTarget(lower, upper float64) (*Target, error)
- func CustomHeartRateTarget(lower, upper float64) (*Target, error)
- func CustomPowerTarget(lower, upper float64) (*Target, error)
- func HeartRateZoneTarget(zone int) *Target
- func PaceTarget(lower, upper float64) (*Target, error)
- func PowerZoneTarget(zone int) *Target
- func SpeedTarget(lower, upper float64) (*Target, error)
- func SwimCSSOffsetTarget(offsetSeconds float64) (*Target, error)
- type TargetType
- type Workout
- type WorkoutSegment
Constants ¶
This section is empty.
Variables ¶
var ( ErrAuthentication = errors.New("garminconnect: authentication failed") ErrTooManyRequests = errors.New("garminconnect: too many requests") ErrConnection = errors.New("garminconnect: connection error") ErrNotFound = errors.New("garminconnect: not found") // also matches ErrConnection ErrInvalidFileFormat = errors.New("garminconnect: invalid file format") ErrInvalidArgument = errors.New("garminconnect: invalid argument") )
Sentinel errors. Check them with errors.Is.
var ( SportRunning = SportType{1, "running", 1} SportCycling = SportType{2, "cycling", 2} SportSwimming = SportType{4, "swimming", 3} SportStrengthTraining = SportType{5, "strength_training", 5} SportCardioTraining = SportType{6, "cardio_training", 6} // fitness equipment SportMultiSport = SportType{10, "multi_sport", 10} SportWalking = SportType{17, "walking", 17} SportHiking = SportType{18, "hiking", 18} )
Sport types from /workout-service/workout/types.
var ExerciseCategories = []string{
"BANDED_EXERCISES",
"BATTLE_ROPE",
"BENCH_PRESS",
"BIKE_OUTDOOR",
"CALF_RAISE",
"CARDIO",
"CARRY",
"CHOP",
"CORE",
"CRUNCH",
"CURL",
"DEADLIFT",
"ELLIPTICAL",
"FLOOR_CLIMB",
"FLYE",
"HIP_RAISE",
"HIP_STABILITY",
"HIP_SWING",
"HYPEREXTENSION",
"INDOOR_BIKE",
"LADDER",
"LATERAL_RAISE",
"LEG_CURL",
"LEG_RAISE",
"LUNGE",
"OLYMPIC_LIFT",
"PLANK",
"PLYO",
"PULL_UP",
"PUSH_UP",
"ROW",
"RUN",
"RUN_INDOOR",
"SANDBAG",
"SHOULDER_PRESS",
"SHOULDER_STABILITY",
"SHRUG",
"SIT_UP",
"SLED",
"SLEDGE_HAMMER",
"SQUAT",
"STAIR_STEPPER",
"SUSPENSION",
"TIRE",
"TOTAL_BODY",
"TRICEPS_EXTENSION",
"WARM_UP",
}
ExerciseCategories lists all distinct exercise categories.
var Exercises = []Exercise{}/* 1527 elements not displayed */
Exercises is every selectable strength exercise from the Garmin Connect workout editor (1527 exercises across 47 categories). Exercise may be "" (the workout shows only the category name).
Functions ¶
func As ¶
func As[T any](raw json.RawMessage, err error) (T, error)
As decodes a raw JSON result into T:
stats, err := garminconnect.As[MyStats](g.GetUserSummary(ctx, "2026-10-01"))
func ParseActivityDetailMetrics ¶
func ParseActivityDetailMetrics(details json.RawMessage) ([]map[string]any, error)
ParseActivityDetailMetrics resolves the positional samples of GetActivityDetails into one map per sample keyed by metric name. Descriptors without a valid metricsIndex are skipped and samples missing a channel omit that key. The duration keys (sumDuration, sumElapsedDuration, sumMovingDuration) differ; pick the one you mean.
func SpeedToMPS ¶
SpeedToMPS converts a "kph" or "mph" speed to m/s.
func StatusCode ¶
StatusCode returns the HTTP status carried by err, or 0.
func TokenFilePath ¶
TokenFilePath returns the token file for a directory or .json path. It rejects "~user" paths and symlinks anywhere in the ancestry, so a planted symlink cannot redirect load/dump/logout.
Types ¶
type ActivityDownloadFormat ¶
type ActivityDownloadFormat int
ActivityDownloadFormat selects the DownloadActivity export format.
const ( FormatOriginal ActivityDownloadFormat = iota // zip with the original FIT file FormatTCX FormatGPX FormatKML FormatCSV // csv of the splits )
type BodyComposition ¶
type BodyComposition struct {
Weight float64
PercentFat *float64
PercentHydration *float64
VisceralFatMass *float64
BoneMass *float64
MuscleMass *float64
BasalMet *float64
ActiveMet *float64
PhysiqueRating *float64
MetabolicAge *float64
VisceralFatRating *float64
BMI *float64
}
BodyComposition holds the optional fields of AddBodyComposition; nil fields are written as FIT "invalid".
type Client ¶
type Client struct {
// SkipStrategies names login strategies to skip, e.g. "mobile+tls".
SkipStrategies map[string]bool
// VerifyLogin validates each strategy's token against the API tier
// before accepting it.
VerifyLogin bool
Log *slog.Logger
// OnTokens, when set, receives the token JSON (as Dumps returns it)
// whenever tokens are obtained or refreshed. It runs outside the
// client's lock, so it may call back into the client.
OnTokens func(tokenJSON string)
// contains filtered or unexported fields
}
Client talks to Garmin Connect: it logs in, holds tokens and signs API calls.
func (*Client) Dump ¶
Dump writes the tokens to disk as 0600 inside a 0700 directory, atomically via an unpredictable temp file, since the refresh token grants persistent account access.
func (*Client) IsAuthenticated ¶
IsAuthenticated reports whether the client holds a token.
func (*Client) Login ¶
func (c *Client) Login(ctx context.Context, email, password string, promptMFA func() (string, error), returnOnMFA bool) (needsMFA bool, err error)
Login runs the strategy chain. With returnOnMFA it returns needsMFA=true instead of calling promptMFA; finish with ResumeLogin.
func (*Client) Request ¶
func (c *Client) Request(ctx context.Context, method, path string, opts *RequestOptions) ([]byte, error)
Request performs an authenticated call against connectapi and returns the raw body (nil for 204 / empty). Errors are *Error values whose Kind is ErrAuthentication (401), ErrTooManyRequests (429), ErrNotFound (404) or ErrConnection.
type DailyCalories ¶
type DailyCalories struct {
CalendarDate string `json:"calendarDate"`
Active *float64 `json:"active"`
Resting *float64 `json:"resting"`
Total float64 `json:"total"`
}
DailyCalories is one day of active + resting (BMR) calories.
type DailyValue ¶
DailyValue is one calendar date with a value.
type EndCondition ¶
type EndCondition struct {
ConditionTypeID int `json:"conditionTypeId"`
ConditionTypeKey string `json:"conditionTypeKey"`
DisplayOrder int `json:"displayOrder"`
Displayable bool `json:"displayable"`
}
EndCondition says when a step ends.
type Error ¶
Error carries the error kind, the HTTP status (0 when not an HTTP failure) and the underlying cause.
type ExecutableStep ¶
type ExecutableStep struct {
Type string `json:"type"` // "ExecutableStepDTO"
StepOrder int `json:"stepOrder"`
StepType *StepType `json:"stepType,omitempty"`
EndCondition *EndCondition `json:"endCondition,omitempty"`
EndConditionValue *float64 `json:"endConditionValue,omitempty"`
TargetType *TargetType `json:"targetType,omitempty"`
TargetValueOne *float64 `json:"targetValueOne,omitempty"`
TargetValueTwo *float64 `json:"targetValueTwo,omitempty"`
ZoneNumber *int `json:"zoneNumber,omitempty"`
SecondaryTargetType *TargetType `json:"secondaryTargetType,omitempty"`
SecondaryTargetValueOne *float64 `json:"secondaryTargetValueOne,omitempty"`
SecondaryTargetValueTwo *float64 `json:"secondaryTargetValueTwo,omitempty"`
SecondaryZoneNumber *int `json:"secondaryZoneNumber,omitempty"`
StrokeType map[string]any `json:"strokeType,omitempty"`
EquipmentType map[string]any `json:"equipmentType,omitempty"`
ChildStepID *int `json:"childStepId,omitempty"`
// Strength steps.
Category string `json:"category,omitempty"`
ExerciseName *string `json:"exerciseName,omitempty"`
WeightValue *float64 `json:"weightValue,omitempty"` // grams
WeightUnit map[string]any `json:"weightUnit,omitempty"`
}
ExecutableStep is a warmup, interval, recovery, cooldown or rest step.
func CooldownStep ¶
func CooldownStep(durationSecs float64, order int) *ExecutableStep
CooldownStep is a timed cooldown.
func DistanceIntervalStep ¶
func DistanceIntervalStep(distanceMeters float64, order int, primary, secondary *Target) (*ExecutableStep, error)
DistanceIntervalStep is an interval that ends after distanceMeters.
func IntervalStep ¶
func IntervalStep(durationSecs float64, order int, primary, secondary *Target) (*ExecutableStep, error)
IntervalStep is a timed interval with optional primary/secondary targets.
func RecoveryStep ¶
func RecoveryStep(durationSecs float64, order int) *ExecutableStep
RecoveryStep is a timed recovery.
func StrengthExerciseStep ¶
func StrengthExerciseStep(category string, order, reps int, exerciseName string, weightKG *float64) *ExecutableStep
StrengthExerciseStep is a rep-based exercise. category/exerciseName come from Exercises; weightKG nil means no target load.
func StrengthRestStep ¶
func StrengthRestStep(durationSecs float64, order int) *ExecutableStep
StrengthRestStep is a timed rest between sets.
func WarmupStep ¶
func WarmupStep(durationSecs float64, order int) *ExecutableStep
WarmupStep is a timed warmup.
type Exercise ¶
type Exercise struct {
Name string `json:"name"`
Category string `json:"category"`
Exercise string `json:"exercise"`
}
Exercise is one strength-exercise catalog entry.
func FindExercises ¶
FindExercises returns exercises whose name contains term, case-insensitively.
func ResolveExercise ¶
ResolveExercise returns the catalog entry with this exact display name.
type Garmin ¶
type Garmin struct {
Client *Client
DisplayName string
FullName string
UnitSystem string
ProfileID int64 // 0 when unknown
// contains filtered or unexported fields
}
Garmin fetches data from Garmin Connect.
func New ¶
New returns a Garmin client. email/password may be empty when a tokenstore will be supplied to Login.
func (*Garmin) AddBodyComposition ¶
func (g *Garmin) AddBodyComposition(ctx context.Context, ts time.Time, bc BodyComposition) (json.RawMessage, error)
AddBodyComposition uploads a weight-scale FIT record. A zero ts means now.
func (*Garmin) AddGearToActivity ¶
func (g *Garmin) AddGearToActivity(ctx context.Context, gearUUID string, activityID int64) (json.RawMessage, error)
AddGearToActivity links gear to an activity.
func (*Garmin) AddHydrationData ¶
func (g *Garmin) AddHydrationData(ctx context.Context, valueML float64, ts time.Time, cdate string) (json.RawMessage, error)
AddHydrationData adds (or with a negative value subtracts) water in ml. With neither ts nor cdate it uses now; with only cdate, midnight local; with only ts, its date; with both they must agree.
func (*Garmin) AddJetlagTrip ¶
func (g *Garmin) AddJetlagTrip(ctx context.Context, start, end string, flights []JetlagFlight) (json.RawMessage, error)
AddJetlagTrip creates a trip; each flight is one leg (a connection is two flights). Garmin may refuse dates overlapping an existing trip with 400. The response carries tripId and flightIds; dailyStatus appears in GetJetlagTrips once travel starts.
func (*Garmin) AddWeighIn ¶
func (g *Garmin) AddWeighIn(ctx context.Context, weight float64, unit string, ts time.Time) (json.RawMessage, error)
AddWeighIn adds a manual weigh-in. unit is "kg" or "lbs"; a zero ts means now.
func (*Garmin) AddWeighInWithTimestamps ¶
func (g *Garmin) AddWeighInWithTimestamps(ctx context.Context, weight float64, unit string, local, gmt time.Time) (json.RawMessage, error)
AddWeighInWithTimestamps adds a weigh-in with explicit local and GMT times; zero values default to now.
func (*Garmin) ConfirmMenstrualPeriodStart ¶
func (g *Garmin) ConfirmMenstrualPeriodStart(ctx context.Context, periodStart string, periodLength, cycleLength int, predictedCycle bool) (json.RawMessage, error)
ConfirmMenstrualPeriodStart confirms a period start, e.g. turning a predicted cycle into a confirmed one. Pass the lengths shown that day.
func (*Garmin) ConnectAPI ¶
func (g *Garmin) ConnectAPI(ctx context.Context, path string, params url.Values) (json.RawMessage, error)
ConnectAPI performs an arbitrary authenticated GET and returns the JSON.
func (*Garmin) CountActivities ¶
CountActivities returns the total number of activities.
func (*Garmin) CreateGear ¶
CreateGear creates gear (e.g. shoes) and returns it.
func (*Garmin) CreateManualActivity ¶
func (g *Garmin) CreateManualActivity(ctx context.Context, start, timeZone, typeKey string, distanceKM float64, durationMin int, name string) (json.RawMessage, error)
CreateManualActivity creates a private activity. typeKey is the activity type key without the "activity_type_" prefix (e.g. "resort_skiing"); start is like "2023-12-02T10:00:00.000"; timeZone like "Europe/Paris".
func (*Garmin) CreateManualActivityFromJSON ¶
func (g *Garmin) CreateManualActivityFromJSON(ctx context.Context, payload any) (json.RawMessage, error)
CreateManualActivityFromJSON creates an activity from a raw payload.
func (*Garmin) DeleteActivity ¶
DeleteActivity deletes an activity.
func (*Garmin) DeleteBloodPressure ¶
func (g *Garmin) DeleteBloodPressure(ctx context.Context, version int64, cdate string) (json.RawMessage, error)
DeleteBloodPressure deletes one measurement.
func (*Garmin) DeleteJetlagTrip ¶
DeleteJetlagTrip deletes a trip.
func (*Garmin) DeleteWeighIn ¶
func (g *Garmin) DeleteWeighIn(ctx context.Context, weightPK int64, cdate string) (json.RawMessage, error)
DeleteWeighIn deletes one weigh-in.
func (*Garmin) DeleteWeighIns ¶
DeleteWeighIns deletes the weigh-ins of cdate and returns how many were deleted. With several on that day nothing is deleted unless deleteAll.
func (*Garmin) DeleteWorkout ¶
DeleteWorkout deletes a workout template from the library.
func (*Garmin) DownloadActivity ¶
func (g *Garmin) DownloadActivity(ctx context.Context, id int64, format ActivityDownloadFormat) ([]byte, error)
DownloadActivity returns the activity export in the requested format.
func (*Garmin) DownloadHealthSnapshot ¶
DownloadHealthSnapshot returns the Health Snapshot ZIP for a date.
func (*Garmin) DownloadWorkout ¶
DownloadWorkout returns a workout as a FIT file.
func (*Garmin) GetActivities ¶
func (g *Garmin) GetActivities(ctx context.Context, start, limit int, activityType, subType string) (json.RawMessage, error)
GetActivities returns activities starting at offset start (0 = most recent). activityType/subType are optional filters ("" to skip).
func (*Garmin) GetActivitiesByDate ¶
func (g *Garmin) GetActivitiesByDate(ctx context.Context, startdate, enddate, activityType, sortOrder string) (json.RawMessage, error)
GetActivitiesByDate returns all activities between startdate and enddate ("" = open), paging 20 at a time like the web UI. activityType (e.g. "running", "cycling") and sortOrder ("asc") are optional.
func (*Garmin) GetActivitiesForDate ¶
GetActivitiesForDate returns activities for a date.
func (*Garmin) GetActivity ¶
GetActivity returns the activity summary, including basic splits.
func (*Garmin) GetActivityDetails ¶
func (g *Garmin) GetActivityDetails(ctx context.Context, id int64, maxChart, maxPoly int) (json.RawMessage, error)
GetActivityDetails returns detail charts (defaults: maxChart 2000, maxPoly 4000). See ParseActivityDetailMetrics.
func (*Garmin) GetActivityExerciseSets ¶
GetActivityExerciseSets returns the exercise sets of an activity.
func (*Garmin) GetActivityGear ¶
GetActivityGear returns the gear used for an activity.
func (*Garmin) GetActivityHRInTimezones ¶
GetActivityHRInTimezones returns time in heart rate zones.
func (*Garmin) GetActivityImages ¶
GetActivityImages returns the photos attached to an activity. Their URLs are presigned and expire after 24 hours.
func (*Garmin) GetActivityPowerInTimezones ¶
func (g *Garmin) GetActivityPowerInTimezones(ctx context.Context, id int64) (json.RawMessage, error)
GetActivityPowerInTimezones returns time in power zones.
func (*Garmin) GetActivitySplitSummaries ¶
GetActivitySplitSummaries returns split summaries.
func (*Garmin) GetActivitySplits ¶
GetActivitySplits returns activity splits.
func (*Garmin) GetActivityTypedSplits ¶
GetActivityTypedSplits returns typed splits (more detail for e.g. bouldering).
func (*Garmin) GetActivityTypes ¶
GetActivityTypes returns all activity types.
func (*Garmin) GetActivityWeather ¶
GetActivityWeather returns the weather during an activity.
func (*Garmin) GetAdaptiveTrainingPlanByID ¶
func (g *Garmin) GetAdaptiveTrainingPlanByID(ctx context.Context, planID int64) (json.RawMessage, error)
GetAdaptiveTrainingPlanByID returns an adaptive training plan.
func (*Garmin) GetAdhocChallenges ¶
GetAdhocChallenges returns historical ad-hoc challenges.
func (*Garmin) GetAllDayEvents ¶
GetAllDayEvents returns daily events for cdate, including auto-detected activities.
func (*Garmin) GetAllDayStress ¶
GetAllDayStress returns all-day stress data for cdate.
func (*Garmin) GetAvailableBadgeChallenges ¶
func (g *Garmin) GetAvailableBadgeChallenges(ctx context.Context, start, limit int) (json.RawMessage, error)
GetAvailableBadgeChallenges returns available badge challenges (start >= 1).
func (*Garmin) GetAvailableBadges ¶
GetAvailableBadges returns badges not yet earned.
func (*Garmin) GetBadgeChallenges ¶
GetBadgeChallenges returns completed badge challenges (start >= 1).
func (*Garmin) GetBloodPressure ¶
func (g *Garmin) GetBloodPressure(ctx context.Context, startdate, enddate string) (json.RawMessage, error)
GetBloodPressure returns blood pressure for startdate..enddate.
func (*Garmin) GetBodyBattery ¶
func (g *Garmin) GetBodyBattery(ctx context.Context, startdate, enddate string) (json.RawMessage, error)
GetBodyBattery returns body battery values for startdate..enddate.
func (*Garmin) GetBodyBatteryEvents ¶
GetBodyBatteryEvents returns body battery events (sleep, activities, naps) for cdate.
func (*Garmin) GetBodyComposition ¶
func (g *Garmin) GetBodyComposition(ctx context.Context, startdate, enddate string) (json.RawMessage, error)
GetBodyComposition returns body composition for startdate..enddate (enddate "" means a single day).
func (*Garmin) GetCaloriesDaily ¶
GetCaloriesDaily returns daily active and resting calories for start..end.
func (*Garmin) GetCyclingFTP ¶
GetCyclingFTP returns the latest cycling Functional Threshold Power.
func (*Garmin) GetDailySteps ¶
GetDailySteps returns daily steps for start..end, splitting ranges over Garmin's 28-day limit into several requests.
func (*Garmin) GetDailyTrainingStatus ¶
GetDailyTrainingStatus returns the training status and acute/chronic load for cdate.
func (*Garmin) GetDailyWeighIns ¶
GetDailyWeighIns returns weigh-ins for cdate.
func (*Garmin) GetDeviceAlarms ¶
GetDeviceAlarms returns the alarms of all devices.
func (*Garmin) GetDeviceLastUsed ¶
GetDeviceLastUsed returns the last used device.
func (*Garmin) GetDeviceSettings ¶
GetDeviceSettings returns settings of a device.
func (*Garmin) GetDeviceSolarData ¶
func (g *Garmin) GetDeviceSolarData(ctx context.Context, deviceID int64, startdate, enddate string) (json.RawMessage, error)
GetDeviceSolarData returns solar input of a device for startdate..enddate (enddate "" = single day view).
func (*Garmin) GetDevices ¶
GetDevices returns the devices registered to the account.
func (*Garmin) GetEarnedBadges ¶
GetEarnedBadges returns all earned badges.
func (*Garmin) GetEnduranceScore ¶
func (g *Garmin) GetEnduranceScore(ctx context.Context, startdate, enddate string) (json.RawMessage, error)
GetEnduranceScore returns the score for one day (enddate "") or weekly aggregates for a range.
func (*Garmin) GetFitnessAgeData ¶
GetFitnessAgeData returns fitness age data for cdate.
func (*Garmin) GetFunctionalThresholdPowerRange ¶
func (g *Garmin) GetFunctionalThresholdPowerRange(ctx context.Context, start, end, sport, aggregation string) (json.RawMessage, error)
GetFunctionalThresholdPowerRange returns FTP history for a sport (default "RUNNING") and aggregation (default "daily").
func (*Garmin) GetGearActivities ¶
func (g *Garmin) GetGearActivities(ctx context.Context, gearUUID string, limit int) (json.RawMessage, error)
GetGearActivities returns activities that used the gear (limit capped at 1000); [] for retired/removed gear.
func (*Garmin) GetGearDefaults ¶
func (g *Garmin) GetGearDefaults(ctx context.Context, userProfileNumber int64) (json.RawMessage, error)
GetGearDefaults returns default gear per activity type.
func (*Garmin) GetGearStats ¶
GetGearStats returns statistics of a gear item; {} for retired/removed gear.
func (*Garmin) GetGoals ¶
func (g *Garmin) GetGoals(ctx context.Context, status string, start, limit int) (json.RawMessage, error)
GetGoals returns all goals with status "active" (default), "future" or "past", paging from the 1-based start (default 1) by limit (default 30).
func (*Garmin) GetGolfClubStats ¶
GetGolfClubStats returns golf clubs and their statistics (default limit 1000).
func (*Garmin) GetGolfScorecard ¶
GetGolfScorecard returns a scorecard's detail.
func (*Garmin) GetGolfShotData ¶
func (g *Garmin) GetGolfShotData(ctx context.Context, scorecardID int64, holes string) (json.RawMessage, error)
GetGolfShotData returns shot data per hole. holes is "" for every hole or holes 1-18 separated by ',' or '-' ("1,2,3"). Garmin drops holes 10-18 from filtered queries, so any of those returns all 18 holes.
func (*Garmin) GetGolfSummary ¶
GetGolfSummary returns golf scorecard summaries (default limit 100).
func (*Garmin) GetGolfUserStats ¶
GetGolfUserStats returns golf statistics such as handicap and strokes gained.
func (*Garmin) GetHRVData ¶
GetHRVData returns heart rate variability data for cdate.
func (*Garmin) GetHRVDataRange ¶
GetHRVDataRange returns HRV data for start..end in one request.
func (*Garmin) GetHeartRateZones ¶
GetHeartRateZones returns heart rate zones for all sport profiles.
func (*Garmin) GetHeartRates ¶
GetHeartRates returns heart rate data for cdate.
func (*Garmin) GetHillScore ¶
func (g *Garmin) GetHillScore(ctx context.Context, startdate, enddate string) (json.RawMessage, error)
GetHillScore returns the score for one day (enddate "") or daily values for a range.
func (*Garmin) GetHydrationData ¶
GetHydrationData returns hydration data for cdate.
func (*Garmin) GetInProgressBadges ¶
GetInProgressBadges returns earned and available badges still in progress, de-duplicated by badgeId (available wins).
func (*Garmin) GetInProgressVirtualChallenges ¶
func (g *Garmin) GetInProgressVirtualChallenges(ctx context.Context, start, limit int) (json.RawMessage, error)
GetInProgressVirtualChallenges returns in-progress virtual challenges (start >= 1).
func (*Garmin) GetIntensityMinutesData ¶
func (g *Garmin) GetIntensityMinutesData(ctx context.Context, cdate string) (json.RawMessage, error)
GetIntensityMinutesData returns intensity minutes for cdate.
func (*Garmin) GetJetlagTrips ¶
GetJetlagTrips returns all Jet Lag Adviser trips with their flights.
func (*Garmin) GetLactateThreshold ¶
func (g *Garmin) GetLactateThreshold(ctx context.Context, latest bool, start, end, aggregation string) (json.RawMessage, error)
GetLactateThreshold returns running lactate threshold data. With latest it returns {"speed_and_heart_rate", "power"}; otherwise the history for start..end (end "" = today) as {"speed", "heart_rate", "power"}.
func (*Garmin) GetLastActivity ¶
GetLastActivity returns the most recent activity, or nil.
func (*Garmin) GetLifestyleLoggingData ¶
func (g *Garmin) GetLifestyleLoggingData(ctx context.Context, cdate string) (json.RawMessage, error)
GetLifestyleLoggingData returns lifestyle logging data for cdate.
func (*Garmin) GetMaxMetrics ¶
GetMaxMetrics returns max metrics (VO2 max etc.) for cdate.
func (*Garmin) GetMaxMetricsRange ¶
func (g *Garmin) GetMaxMetricsRange(ctx context.Context, start, end string) (json.RawMessage, error)
GetMaxMetricsRange returns max metrics for start..end.
func (*Garmin) GetMenstrualCalendarData ¶
func (g *Garmin) GetMenstrualCalendarData(ctx context.Context, startdate, enddate string) (json.RawMessage, error)
GetMenstrualCalendarData returns cycles with days in startdate..enddate (Garmin rejects windows over 90 days).
func (*Garmin) GetMenstrualCycleSummary ¶
func (g *Garmin) GetMenstrualCycleSummary(ctx context.Context, date string) (json.RawMessage, error)
GetMenstrualCycleSummary returns the cycle summary for date.
func (*Garmin) GetMenstrualDataForDate ¶
GetMenstrualDataForDate returns the menstrual day view for a date.
func (*Garmin) GetMenstrualLastConfirmed ¶
func (g *Garmin) GetMenstrualLastConfirmed(ctx context.Context, date string) (json.RawMessage, error)
GetMenstrualLastConfirmed returns the last confirmed cycle as of date.
func (*Garmin) GetMenstrualReports ¶
func (g *Garmin) GetMenstrualReports(ctx context.Context, date string, cycles int, next bool, reportType, today string) (json.RawMessage, error)
GetMenstrualReports returns reports for 1, 6 or 12 cycles ending at date. reportType defaults to "CYCLE", today to the current date.
func (*Garmin) GetMorningTrainingReadiness ¶
func (g *Garmin) GetMorningTrainingReadiness(ctx context.Context, cdate string) (json.RawMessage, error)
GetMorningTrainingReadiness returns the readiness computed right after waking (inputContext AFTER_WAKEUP_RESET), falling back to the first entry on devices that do not set inputContext. nil when there is no data.
func (*Garmin) GetNextScheduledWorkout ¶
GetNextScheduledWorkout returns the earliest workout scheduled today or later in this or next month, or {} when none. Adaptive/Coach plans may show sessions the calendar service does not return yet.
func (*Garmin) GetNonCompletedBadgeChallenges ¶
func (g *Garmin) GetNonCompletedBadgeChallenges(ctx context.Context, start, limit int) (json.RawMessage, error)
GetNonCompletedBadgeChallenges returns non-completed badge challenges (start >= 1).
func (*Garmin) GetNutritionDailyFoodLog ¶
func (g *Garmin) GetNutritionDailyFoodLog(ctx context.Context, cdate string) (json.RawMessage, error)
GetNutritionDailyFoodLog returns the food log for cdate.
func (*Garmin) GetNutritionDailyMeals ¶
GetNutritionDailyMeals returns the meals for cdate.
func (*Garmin) GetNutritionDailySettings ¶
func (g *Garmin) GetNutritionDailySettings(ctx context.Context, cdate string) (json.RawMessage, error)
GetNutritionDailySettings returns nutrition settings for cdate.
func (*Garmin) GetPersonalRecord ¶
GetPersonalRecord returns personal records. For running, typeId 1..7 is 1 km, 1 mile, 5 km, 10 km, half marathon, marathon, longest run.
func (*Garmin) GetPowerZones ¶
GetPowerZones returns power zones for all sports.
func (*Garmin) GetPowerZonesForSport ¶
GetPowerZonesForSport returns power zones for a sport key, e.g. "CYCLING".
func (*Garmin) GetPregnancySummary ¶
GetPregnancySummary returns the pregnancy snapshot.
func (*Garmin) GetPrimaryTrainingDevice ¶
GetPrimaryTrainingDevice returns the primary training device and the priority of all devices.
func (*Garmin) GetProgressSummaryBetweenDates ¶
func (g *Garmin) GetProgressSummaryBetweenDates(ctx context.Context, startdate, enddate, metric string, groupByActivities bool) (json.RawMessage, error)
GetProgressSummaryBetweenDates returns lifetime progress for a metric ("elevationGain", "duration", "distance" (default), "movingDuration").
func (*Garmin) GetRHRDaily ¶
GetRHRDaily returns daily resting heart rate for start..end (up to ~1 year) in one request.
func (*Garmin) GetRacePredictions ¶
func (g *Garmin) GetRacePredictions(ctx context.Context, startdate, enddate, predType string) (json.RawMessage, error)
GetRacePredictions returns 5k/10k/half/marathon predictions. Pass all empty for the latest, or all three (predType "daily" or "monthly", range at most one year) for history.
func (*Garmin) GetRespirationData ¶
GetRespirationData returns respiration data for cdate.
func (*Garmin) GetRunningTolerance ¶
func (g *Garmin) GetRunningTolerance(ctx context.Context, startdate, enddate, aggregation string) (json.RawMessage, error)
GetRunningTolerance returns running tolerance for a range; aggregation is "daily" or "weekly" (default).
func (*Garmin) GetScheduledWorkoutByID ¶
GetScheduledWorkoutByID returns a scheduled workout.
func (*Garmin) GetScheduledWorkouts ¶
func (g *Garmin) GetScheduledWorkouts(ctx context.Context, year, month int) (json.RawMessage, error)
GetScheduledWorkouts returns the calendar of a month (1-12).
func (*Garmin) GetSleepDaily ¶
GetSleepDaily returns daily sleep summaries for start..end, chunked by 28 days, de-duplicated and sorted by calendarDate.
func (*Garmin) GetSleepData ¶
GetSleepData returns sleep data for cdate. Some CN accounts report the *Local timestamps offset twice; prefer the *GMT fields when in doubt.
func (*Garmin) GetSpo2Data ¶
GetSpo2Data returns SpO2 data for cdate; a string lastSevenDaysAvgSpO2 is converted to a number.
func (*Garmin) GetStatsAndBody ¶
GetStatsAndBody merges the daily summary with the body composition average.
func (*Garmin) GetStepsData ¶
GetStepsData returns the step chart data for cdate.
func (*Garmin) GetStressData ¶
GetStressData returns stress data for cdate (same endpoint as GetAllDayStress).
func (*Garmin) GetTrainingFourWeekLoadBalance ¶
func (g *Garmin) GetTrainingFourWeekLoadBalance(ctx context.Context, cdate string) (json.RawMessage, error)
GetTrainingFourWeekLoadBalance returns the load focus for the four weeks ending at cdate.
func (*Garmin) GetTrainingLoadActivities ¶
func (g *Garmin) GetTrainingLoadActivities(ctx context.Context, startdate, enddate string, metrics []string, activityType string) (json.RawMessage, error)
GetTrainingLoadActivities returns activities with training load metrics. metrics nil uses the defaults; an empty non-nil slice requests none.
func (*Garmin) GetTrainingPlanByID ¶
GetTrainingPlanByID returns a phased training plan.
func (*Garmin) GetTrainingPlans ¶
GetTrainingPlans returns all available training plans.
func (*Garmin) GetTrainingReadiness ¶
GetTrainingReadiness returns training readiness snapshots for cdate.
func (*Garmin) GetTrainingStatus ¶
GetTrainingStatus returns aggregated training status for cdate.
func (*Garmin) GetUserProfile ¶
GetUserProfile returns all user settings.
func (*Garmin) GetUserSummary ¶
GetUserSummary returns the daily activity summary for cdate (YYYY-MM-DD).
func (*Garmin) GetUserprofileSettings ¶
GetUserprofileSettings returns user profile settings.
func (*Garmin) GetWeeklyIntensityMinutes ¶
func (g *Garmin) GetWeeklyIntensityMinutes(ctx context.Context, start, end string) (json.RawMessage, error)
GetWeeklyIntensityMinutes returns weekly intensity minute aggregates.
func (*Garmin) GetWeeklySteps ¶
func (g *Garmin) GetWeeklySteps(ctx context.Context, end string, weeks int) (json.RawMessage, error)
GetWeeklySteps returns weekly step aggregates for weeks ending at end.
func (*Garmin) GetWeeklyStress ¶
func (g *Garmin) GetWeeklyStress(ctx context.Context, end string, weeks int) (json.RawMessage, error)
GetWeeklyStress returns weekly stress aggregates for weeks ending at end.
func (*Garmin) GetWeighIns ¶
func (g *Garmin) GetWeighIns(ctx context.Context, startdate, enddate string) (json.RawMessage, error)
GetWeighIns returns weigh-ins between startdate and enddate.
func (*Garmin) GetWorkoutByID ¶
GetWorkoutByID returns a workout.
func (*Garmin) GetWorkouts ¶
GetWorkouts returns workouts from offset start (default limit 100).
func (*Garmin) ImportActivity ¶
ImportActivity uploads a file as an import, with Garmin Connect Mobile headers, so it is not re-exported to third parties like Strava. A duplicate is reported as an error with StatusCode 409.
func (*Garmin) InitMenstrualCycleSetup ¶
func (g *Garmin) InitMenstrualCycleSetup(ctx context.Context, periodStart string, periodLength, cycleLength int) (json.RawMessage, error)
InitMenstrualCycleSetup starts cycle tracking with the first confirmed period. Not for editing an already configured account; change tracking flags with UpdateMenstrualSettings.
func (*Garmin) Login ¶
Login authenticates. tokenstore is a token directory/file path or inline token JSON (falls back to $GARMINTOKENS); cached tokens are used when valid, otherwise it logs in with credentials and persists new tokens. needsMFA is true only with WithReturnOnMFA.
func (*Garmin) Logout ¶
Logout clears in-memory auth state and deletes the cached token file (the directory and other files stay). It does not revoke tokens at Garmin.
func (*Garmin) PushWorkoutToDevice ¶
func (g *Garmin) PushWorkoutToDevice(ctx context.Context, workoutID, deviceID int64) (json.RawMessage, error)
PushWorkoutToDevice sends a workout to a device. workoutID 0 pushes the latest workout in the library; deviceID 0 picks the last used device.
func (*Garmin) QueryGarminGraphQL ¶
QueryGarminGraphQL posts a GraphQL request body ({"query": ..., "variables": ...}).
func (*Garmin) RemoveGearFromActivity ¶
func (g *Garmin) RemoveGearFromActivity(ctx context.Context, gearUUID string, activityID int64) (json.RawMessage, error)
RemoveGearFromActivity unlinks gear from an activity.
func (*Garmin) RequestReload ¶
RequestReload asks Garmin to reload offloaded data for cdate.
func (*Garmin) ResumeLogin ¶
ResumeLogin completes a login that returned needsMFA and persists tokens to the tokenstore path given to Login, if any.
func (*Garmin) ScheduleWorkout ¶
func (g *Garmin) ScheduleWorkout(ctx context.Context, workoutID int64, date string) (json.RawMessage, error)
ScheduleWorkout puts a workout on the calendar on date (YYYY-MM-DD).
func (*Garmin) SetActivityDescription ¶
func (g *Garmin) SetActivityDescription(ctx context.Context, id int64, description string) (json.RawMessage, error)
SetActivityDescription sets an activity's description.
func (*Garmin) SetActivityExerciseSets ¶
func (g *Garmin) SetActivityExerciseSets(ctx context.Context, id int64, payload any) (json.RawMessage, error)
SetActivityExerciseSets replaces all exercise sets of an activity. payload has the shape GetActivityExerciseSets returns.
func (*Garmin) SetActivityName ¶
func (g *Garmin) SetActivityName(ctx context.Context, id int64, title string) (json.RawMessage, error)
SetActivityName renames an activity.
func (*Garmin) SetActivityType ¶
func (g *Garmin) SetActivityType(ctx context.Context, id int64, typeID int, typeKey string, parentTypeID int) (json.RawMessage, error)
SetActivityType changes an activity's type.
func (*Garmin) SetBloodPressure ¶
func (g *Garmin) SetBloodPressure(ctx context.Context, systolic, diastolic, pulse int, ts time.Time, notes string) (json.RawMessage, error)
SetBloodPressure adds a measurement. pulse 0 omits the heart rate; a zero ts means now.
func (*Garmin) SetGearDefault ¶
func (g *Garmin) SetGearDefault(ctx context.Context, activityType, gearUUID string, defaultGear bool) (json.RawMessage, error)
SetGearDefault makes gear the default for an activity type (e.g. "RUNNING"), or removes that default when defaultGear is false.
func (*Garmin) UnscheduleWorkout ¶
func (g *Garmin) UnscheduleWorkout(ctx context.Context, scheduledWorkoutID int64) (json.RawMessage, error)
UnscheduleWorkout removes a scheduled workout, keeping the template.
func (*Garmin) UpdateJetlagTrip ¶
func (g *Garmin) UpdateJetlagTrip(ctx context.Context, tripID int64, start, end string, flights []JetlagFlight) (json.RawMessage, error)
UpdateJetlagTrip replaces a trip, so flights must hold every flight; keep the FlightID of each flight that stays.
func (*Garmin) UpdateMenstrualCalendar ¶
func (g *Garmin) UpdateMenstrualCalendar(ctx context.Context, startdate, enddate string, cycleDates [][]string, today string) (json.RawMessage, error)
UpdateMenstrualCalendar replaces period dates in startdate..enddate. Each inner list is one period of consecutive dates; omitted confirmed days in range are removed. Do not post predicted cycles as confirmed.
func (*Garmin) UpdateMenstrualDailyLog ¶
func (g *Garmin) UpdateMenstrualDailyLog(ctx context.Context, date string, l MenstrualDailyLog) (json.RawMessage, error)
UpdateMenstrualDailyLog replaces the daily log of date. Read GetMenstrualDataForDate first and pass every value to keep.
func (*Garmin) UpdateMenstrualSettings ¶
func (g *Garmin) UpdateMenstrualSettings(ctx context.Context, settings map[string]any, userSettingsID int64) (json.RawMessage, error)
UpdateMenstrualSettings overlays settings onto the stored userMenstrualCycleSettings. userSettingsID 0 uses the profile's id.
func (*Garmin) UpdateWorkout ¶
UpdateWorkout replaces a workout in place (keeping its id, so schedules stay valid). workout must be the complete structure; workoutId is forced to id.
func (*Garmin) UploadActivity ¶
UploadActivity uploads a FIT, GPX or TCX file.
func (*Garmin) UploadWorkout ¶
UploadWorkout creates a workout from a *Workout (see NewWorkout), a JSON string, json.RawMessage or any value that marshals to a JSON object/array.
type GearSpec ¶
type GearSpec struct {
GearType string // e.g. "SHOES"
Brand string
Model string
Name string
FirstUseDate string // YYYY-MM-DD
UsageType string // default "DISTANCE"
MaxUsageKM float64 // retirement threshold; 0 = none
MaxUsageMin float64 // retirement threshold; 0 = none
Notes string
// ActivityTypeKeys are lowercase keys (e.g. "running") the gear becomes
// the default for.
ActivityTypeKeys []string
}
GearSpec describes new gear for CreateGear. Only GearType "SHOES" and UsageType "DISTANCE" are confirmed against a real account; other values are likely SCREAMING_SNAKE_CASE too.
type JetlagFlight ¶
type JetlagFlight struct {
FlightID int64 `json:"flightId,omitempty"`
TripID int64 `json:"tripId,omitempty"`
OriginLocation string `json:"originLocation"`
OriginTimezone string `json:"originTimezone"`
OriginTimestamp string `json:"originTimestamp"`
DestinationLocation string `json:"destinationLocation"`
DestinationTimezone string `json:"destinationTimezone"`
DestinationTimestamp string `json:"destinationTimestamp"`
}
JetlagFlight is one flight leg. Timezones are UTC offsets at that place on that date ("-07:00"); timestamps are local times without an offset ("2026-10-04T15:20:00"). Garmin does not geocode the free-text locations.
type MenstrualDailyLog ¶
type MenstrualDailyLog struct {
Symptoms []string
Moods []string
Flow string
Discharge []string
SexDrive string
SexualActivity string
Notes *string
OvulationDay *bool
}
MenstrualDailyLog is a full-day snapshot: Garmin clears omitted lists and enums. Notes nil keeps the stored note, "" clears it. OvulationDay nil is stored as false.
type Option ¶
type Option func(*Garmin)
Option configures New.
func WithLogger ¶
WithLogger sets the logger (default: discard).
func WithPromptMFA ¶
WithPromptMFA sets the callback that returns an MFA code during Login.
func WithRetry ¶
WithRetry sets retries for transient 5xx/network errors on GET calls (default 3, 1s..10s backoff). attempts=0 disables. 401/429/4xx never retry.
func WithReturnOnMFA ¶
func WithReturnOnMFA() Option
WithReturnOnMFA makes Login return needsMFA=true instead of prompting; finish with ResumeLogin.
func WithTokenSaver ¶
WithTokenSaver calls fn with the token JSON whenever tokens are obtained or refreshed, so a service can persist them (e.g. per account in a database) and pass them back to Login later.
func WithVerifyLogin ¶
WithVerifyLogin(false) restores the legacy "first token wins" login.
type RepeatGroup ¶
type RepeatGroup struct {
Type string `json:"type"` // "RepeatGroupDTO"
StepOrder int `json:"stepOrder"`
StepType *StepType `json:"stepType,omitempty"`
NumberOfIterations int `json:"numberOfIterations"`
WorkoutSteps []Step `json:"workoutSteps"`
EndCondition *EndCondition `json:"endCondition,omitempty"`
EndConditionValue *float64 `json:"endConditionValue,omitempty"`
ChildStepID *int `json:"childStepId,omitempty"`
SmartRepeat bool `json:"smartRepeat"`
SkipLastRestStep *bool `json:"skipLastRestStep,omitempty"`
}
RepeatGroup repeats its steps NumberOfIterations times.
func NewRepeatGroup ¶
func NewRepeatGroup(iterations int, steps []Step, order int, skipLastRest *bool) *RepeatGroup
NewRepeatGroup repeats steps; skipLastRest optionally drops the final recovery/rest step.
func StrengthSet ¶
func StrengthSet(category string, order, sets, reps int, restSecs float64, exerciseName string, weightKG *float64) *RepeatGroup
StrengthSet is one "N sets" block: a repeat group at order holding the exercise (order+1) and rest (order+2). Advance your order counter by 3.
type RequestOptions ¶
type RequestOptions struct {
Params url.Values
Headers map[string]string
Body []byte
ContentType string
}
RequestOptions configures a raw API call.
type SportType ¶
type SportType struct {
SportTypeID int `json:"sportTypeId"`
SportTypeKey string `json:"sportTypeKey"`
DisplayOrder int `json:"displayOrder,omitempty"`
}
SportType identifies a workout sport.
type Step ¶
type Step interface {
// contains filtered or unexported methods
}
Step is an ExecutableStep or a RepeatGroup.
type StepType ¶
type StepType struct {
StepTypeID int `json:"stepTypeId"`
StepTypeKey string `json:"stepTypeKey"`
DisplayOrder int `json:"displayOrder"`
}
StepType identifies a step kind.
type Target ¶
type Target struct {
// contains filtered or unexported fields
}
Target is an intensity target; build one with the *Target functions.
func CadenceTarget ¶
CadenceTarget: steps (running) or revolutions (cycling) per minute.
func CustomHeartRateTarget ¶
CustomHeartRateTarget: beats per minute.
func CustomPowerTarget ¶
CustomPowerTarget: watts.
func HeartRateZoneTarget ¶
HeartRateZoneTarget uses one of the user's configured heart rate zones.
func PaceTarget ¶
PaceTarget: m/s (see PaceToMPS), so the slower pace is the lower limit.
func PowerZoneTarget ¶
PowerZoneTarget uses one of the user's configured power zones.
func SwimCSSOffsetTarget ¶
SwimCSSOffsetTarget is a secondary-only swim target: a signed pace offset in seconds from Critical Swim Speed (positive = slower).
type TargetType ¶
type TargetType struct {
WorkoutTargetTypeID int `json:"workoutTargetTypeId"`
WorkoutTargetTypeKey string `json:"workoutTargetTypeKey"`
DisplayOrder int `json:"displayOrder"`
}
TargetType identifies a step's intensity target.
type Workout ¶
type Workout struct {
WorkoutName string `json:"workoutName"`
SportType SportType `json:"sportType"`
EstimatedDurationInSecs int `json:"estimatedDurationInSecs"`
WorkoutSegments []WorkoutSegment `json:"workoutSegments"`
Author map[string]any `json:"author"`
Description *string `json:"description,omitempty"`
}
Workout is the upload body of UploadWorkout.
type WorkoutSegment ¶
type WorkoutSegment struct {
SegmentOrder int `json:"segmentOrder"`
SportType SportType `json:"sportType"`
WorkoutSteps []Step `json:"workoutSteps"`
}
WorkoutSegment holds the steps of one sport.