connect

package module
v0.0.0-...-3427ae2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 6, 2023 License: MIT Imports: 18 Imported by: 0

README

garmin-connect

Golang client for the Garmin Connect API.

This is nothing but a proof of concept, and the API may change at any time.

GoDoc

Install

The connect CLI app can be installed using go install, and the package using go get.

go install github.com/benammann/garmin-connect-go/connect@latest
go get github.com/benammann/garmin-connect-go@latest

Documentation

Overview

Package connect provides access to the unofficial Garmin Connect API. This is not supported or endorsed by Garmin Ltd. The API may change or stop working at any time. Please use responsible.

Index

Constants

View Source
const (
	// ErrForbidden will be returned if the client doesn't have access to the
	// requested ressource.
	ErrForbidden = Error("forbidden")

	// ErrNotFound will be returned if the requested ressource could not be
	// found.
	ErrNotFound = Error("not found")

	// ErrBadRequest will be returned if Garmin returned a status code 400.
	ErrBadRequest = Error("bad request")

	// ErrNoCredentials will be returned if credentials are needed - but none
	// are set.
	ErrNoCredentials = Error("no credentials set")

	// ErrNotAuthenticated will be returned is the client is not
	// authenticated as required by the request. Remember to call
	// Authenticate().
	ErrNotAuthenticated = Error("client is not authenticated")

	// ErrWrongCredentials will be returned if the username and/or
	// password is not recognized by Garmin Connect.
	ErrWrongCredentials = Error("username and/or password not recognized")
)
View Source
const (
	// ErrUnknownFormat will be returned if the activity file format is unknown.
	ErrUnknownFormat = Error("Unknown format")
)

Variables

This section is empty.

Functions

This section is empty.

Types

type Activity

type Activity struct {
	ID               int          `json:"activityId"`
	ActivityName     string       `json:"activityName"`
	Description      string       `json:"description"`
	StartLocal       Time         `json:"startTimeLocal"`
	StartGMT         Time         `json:"startTimeGMT"`
	ActivityType     ActivityType `json:"activityType"`
	Distance         float64      `json:"distance"` // meter
	Duration         float64      `json:"duration"`
	ElapsedDuration  float64      `json:"elapsedDuration"`
	MovingDuration   float64      `json:"movingDuration"`
	AverageSpeed     float64      `json:"averageSpeed"`
	MaxSpeed         float64      `json:"maxSpeed"`
	OwnerID          int          `json:"ownerId"`
	Calories         float64      `json:"calories"`
	AverageHeartRate float64      `json:"averageHR"`
	MaxHeartRate     float64      `json:"maxHR"`
	DeviceID         int          `json:"deviceId"`
}

Activity describes a Garmin Connect activity.

type ActivityFormat

type ActivityFormat int

ActivityFormat is a file format for importing and exporting activities.

const (
	// ActivityFormatFIT is the "original" Garmin format.
	ActivityFormatFIT ActivityFormat = iota

	// ActivityFormatTCX is Training Center XML (TCX) format.
	ActivityFormatTCX

	// ActivityFormatGPX will export as GPX - the GPS Exchange Format.
	ActivityFormatGPX

	// ActivityFormatKML will export KML files compatible with Google Earth.
	ActivityFormatKML

	// ActivityFormatCSV will export splits as CSV.
	ActivityFormatCSV
)

func FormatFromExtension

func FormatFromExtension(extension string) (ActivityFormat, error)

FormatFromExtension tries to guess the format from a file extension.

func FormatFromFilename

func FormatFromFilename(filename string) (ActivityFormat, error)

FormatFromFilename tries to guess the format based on a filename (or path).

func (ActivityFormat) Extension

func (f ActivityFormat) Extension() string

Extension returns an appropriate filename extension for format.

type ActivityHrZones

type ActivityHrZones struct {
	TimeInZone      time.Duration `json:"secsInZone"`
	ZoneLowBoundary int           `json:"zoneLowBoundary"`
	ZoneNumber      int           `json:"zoneNumber"`
}

ActivityHrZones describes the heart-rate zones during an activity.

type ActivityType

type ActivityType struct {
	TypeID       int    `json:"typeId"`
	TypeKey      string `json:"typeKey"`
	ParentTypeID int    `json:"parentTypeId"`
	SortOrder    int    `json:"sortOrder"`
}

ActivityType describes the type of activity.

type ActivityWeather

type ActivityWeather struct {
	Temperature               int     `json:"temp"`
	ApparentTemperature       int     `json:"apparentTemp"`
	DewPoint                  int     `json:"dewPoint"`
	RelativeHumidity          int     `json:"relativeHumidity"`
	WindDirection             int     `json:"windDirection"`
	WindDirectionCompassPoint string  `json:"windDirectionCompassPoint"`
	WindSpeed                 int     `json:"windSpeed"`
	Latitude                  float64 `json:"latitude"`
	Longitude                 float64 `json:"longitude"`
}

ActivityWeather describes the weather during an activity.

type AdhocChallenge

type AdhocChallenge struct {
	SocialChallengeStatusID       int      `json:"socialChallengeStatusId"`
	SocialChallengeActivityTypeID int      `json:"socialChallengeActivityTypeId"`
	SocialChallengeType           int      `json:"socialChallengeType"`
	Name                          string   `json:"adHocChallengeName"`
	Description                   string   `json:"adHocChallengeDesc"`
	OwnerProfileID                int      `json:"ownerUserProfileId"`
	UUID                          string   `json:"uuid"`
	Start                         Time     `json:"startDate"`
	End                           Time     `json:"endDate"`
	DurationTypeID                int      `json:"durationTypeId"`
	UserRanking                   int      `json:"userRanking"`
	Players                       []Player `json:"players"`
}

AdhocChallenge is a user-initiated challenge between 2 or more participants.

type AdhocChallengeInvitation

type AdhocChallengeInvitation struct {
	AdhocChallenge `json:",inline"`

	UUID               string `json:"adHocChallengeUuid"`
	InviteID           int    `json:"adHocChallengeInviteId"`
	InvitorName        string `json:"invitorName"`
	InvitorID          int    `json:"invitorId"`
	InvitorDisplayName string `json:"invitorDisplayName"`
	InviteeID          int    `json:"inviteeId"`
	UserImageURL       string `json:"userImageUrl"`
}

AdhocChallengeInvitation is a ad-hoc challenge invitation.

type Badge

type Badge struct {
	ID                 int     `json:"badgeId"`
	Key                string  `json:"badgeKey"`
	Name               string  `json:"badgeName"`
	CategoryID         int     `json:"badgeCategoryId"`
	DifficultyID       int     `json:"badgeDifficultyId"`
	Points             int     `json:"badgePoints"`
	TypeID             []int   `json:"badgeTypeIds"`
	SeriesID           int     `json:"badgeSeriesId"`
	Start              Time    `json:"badgeStartDate"`
	End                Time    `json:"badgeEndDate"`
	UserProfileID      int     `json:"userProfileId"`
	FullName           string  `json:"fullName"`
	DisplayName        string  `json:"displayName"`
	EarnedDate         Time    `json:"badgeEarnedDate"`
	EarnedNumber       int     `json:"badgeEarnedNumber"`
	Viewed             bool    `json:"badgeIsViewed"`
	Progress           float64 `json:"badgeProgressValue"`
	Target             float64 `json:"badgeTargetValue"`
	UnitID             int     `json:"badgeUnitId"`
	BadgeAssocTypeID   int     `json:"badgeAssocTypeId"`
	BadgeAssocDataID   string  `json:"badgeAssocDataId"`
	BadgeAssocDataName string  `json:"badgeAssocDataName"`
	EarnedByMe         bool    `json:"earnedByMe"`
	RelatedBadges      []Badge `json:"relatedBadges"`
	Connections        []Badge `json:"connections"`
}

Badge describes a badge.

type BadgeAssocType

type BadgeAssocType struct {
	ID  int    `json:"badgeAssocTypeId"`
	Key string `json:"badgeAssocTypeKey"`
}

type BadgeAttributes

type BadgeAttributes struct {
	BadgeTypes        []BadgeType       `json:"badgeTypes"`
	BadgeCategories   []BadgeCategory   `json:"badgeCategories"`
	BadgeDifficulties []BadgeDifficulty `json:"badgeDifficulties"`
	BadgeUnits        []BadgeUnit       `json:"badgeUnits"`
	BadgeAssocTypes   []BadgeAssocType  `json:"badgeAssocTypes"`
}

type BadgeCategory

type BadgeCategory struct {
	ID  int    `json:"badgeCategoryId"`
	Key string `json:"badgeCategoryKey"`
}

type BadgeDifficulty

type BadgeDifficulty struct {
	ID     int    `json:"badgeDifficultyId"`
	Key    string `json:"badgeDifficultyKey"`
	Points int    `json:"badgePoints"`
}

type BadgeStatus

type BadgeStatus struct {
	ProfileID             int     `json:"userProfileId"`
	Fullname              string  `json:"fullName"`
	DisplayName           string  `json:"displayName"`
	ProUser               bool    `json:"userPro"`
	ProfileImageURLLarge  string  `json:"profileImageUrlLarge"`
	ProfileImageURLMedium string  `json:"profileImageUrlMedium"`
	ProfileImageURLSmall  string  `json:"profileImageUrlSmall"`
	Level                 int     `json:"userLevel"`
	LevelUpdateTime       Time    `json:"levelUpdateDate"`
	Point                 int     `json:"userPoint"`
	Badges                []Badge `json:"badges"`
}

BadgeStatus is the badge status for a Connect user.

type BadgeType

type BadgeType struct {
	ID  int    `json:"badgeTypeId"`
	Key string `json:"badgeTypeKey"`
}

type BadgeUnit

type BadgeUnit struct {
	ID  int    `json:"badgeUnitId"`
	Key string `json:"badgeUnitKey"`
}

type BiometricProfile

type BiometricProfile struct {
	UserID        int     `json:"userId"`
	Height        float64 `json:"height"`
	Weight        float64 `json:"weight"` // grams
	VO2Max        float64 `json:"vo2Max"`
	VO2MaxCycling float64 `json:"vo2MaxCycling"`
}

BiometricProfile holds key biometric data.

type CalendarItem

type CalendarItem struct {
	ID                       int     `json:"id"`
	ItemType                 string  `json:"itemType"`
	ActivityTypeID           int     `json:"activityTypeId"`
	Title                    string  `json:"title"`
	Date                     Date    `json:"date"`
	Duration                 int     `json:"duration"`
	Distance                 int     `json:"distance"`
	Calories                 int     `json:"calories"`
	StartTimestampLocal      Time    `json:"startTimestampLocal"`
	ElapsedDuration          float64 `json:"elapsedDuration"`
	Strokes                  float64 `json:"strokes"`
	MaxSpeed                 float64 `json:"maxSpeed"`
	ShareableEvent           bool    `json:"shareableEvent"`
	AutoCalcCalories         bool    `json:"autoCalcCalories"`
	ProtectedWorkoutSchedule bool    `json:"protectedWorkoutSchedule"`
	IsParent                 bool    `json:"isParent"`
}

CalendarItem describes an activity displayed on a Garmin Connect calendar

type CalendarMonth

type CalendarMonth struct {
	StartDayOfMonth      int            `json:"startDayOfMonth"`
	NumOfDaysInMonth     int            `json:"numOfDaysInMonth"`
	NumOfDaysInPrevMonth int            `json:"numOfDaysInPrevMonth"`
	Month                int            `json:"month"`
	Year                 int            `json:"year"`
	CalendarItems        []CalendarItem `json:"calendarItems"`
}

CalendarMonth describes a Garmin Conenct calendar month

type CalendarWeek

type CalendarWeek struct {
	StartDate        Date           `json:"startDate"`
	EndDate          Date           `json:"endDate"`
	NumOfDaysInMonth int            `json:"numOfDaysInMonth"`
	CalendarItems    []CalendarItem `json:"calendarItems"`
}

CalendarWeek describes a Garmin Connect calendar week

type CalendarYear

type CalendarYear struct {
	StartDayOfJanuary int           `json:"startDayofJanuary"`
	LeapYear          bool          `json:"leapYear"`
	YearItems         []YearItem    `json:"yearItems"`
	YearSummaries     []YearSummary `json:"yearSummaries"`
}

CalendarYear describes a Garmin Connect calendar year

type Client

type Client struct {
	Email     string         `json:"email"`
	Password  string         `json:"password"`
	SessionID string         `json:"sessionID"`
	Profile   *SocialProfile `json:"socialProfile"`

	// LoadBalancerID is the load balancer ID set by Cloudflare in front of
	// Garmin Connect. This must be preserves across requests. A session key
	// is only valid with a corresponding loadbalancer key.
	LoadBalancerID string `json:"cflb"`
	// contains filtered or unexported fields
}

Client can be used to access the unofficial Garmin Connect API.

func NewClient

func NewClient(options ...Option) *Client

NewClient returns a new client for accessing the unofficial Garmin Connect API.

func (*Client) AcceptConnection

func (c *Client) AcceptConnection(connectionRequestID int) error

AcceptConnection will accept a pending connection.

func (*Client) Activities

func (c *Client) Activities(displayName string, start int, limit int) ([]Activity, error)

Activities will list activities for displayName. If displayName is empty, the authenticated user will be used.

func (*Client) Activity

func (c *Client) Activity(activityID int) (*Activity, error)

Activity will retrieve details about an activity.

func (*Client) ActivityHrZones

func (c *Client) ActivityHrZones(activityID int) ([]ActivityHrZones, error)

ActivityHrZones returns the reported heart-rate zones for an activity.

func (*Client) ActivityWeather

func (c *Client) ActivityWeather(activityID int) (*ActivityWeather, error)

ActivityWeather returns the reported weather for an activity.

func (*Client) AddGoal

func (c *Client) AddGoal(displayName string, goal Goal) error

AddGoal will add a new goal. If displayName is empty, the currently authenticated user will be used.

func (*Client) AddUserWeight

func (c *Client) AddUserWeight(date time.Time, weight float64) error

AddUserWeight will add a manual weight in. weight is in grams to match Weightin.

func (*Client) AdhocChallenge

func (c *Client) AdhocChallenge(uuid string) (*AdhocChallenge, error)

AdhocChallenge will retrieve details for challenge with uuid.

func (*Client) AdhocChallengeInvitationRespond

func (c *Client) AdhocChallengeInvitationRespond(inviteID int, accept bool) error

AdhocChallengeInvitationRespond will respond to a ad-hoc challenge. If accept is false, the challenge will be declined.

func (*Client) AdhocChallengeInvites

func (c *Client) AdhocChallengeInvites() ([]AdhocChallengeInvitation, error)

AdhocChallengeInvites list Ad-Hoc challenges awaiting response.

func (*Client) AdhocChallenges

func (c *Client) AdhocChallenges() ([]AdhocChallenge, error)

AdhocChallenges will list the currently non-completed Ad-Hoc challenges. Please note that Players will not be populated, use AdhocChallenge() to retrieve players for a challenge.

func (*Client) Authenticate

func (c *Client) Authenticate() error

Authenticate using a Garmin Connect username and password provided by the Credentials option function.

func (*Client) BadgeAttributes

func (c *Client) BadgeAttributes() (*BadgeAttributes, error)

BadgeAttributes retrieves a list of badge attributes. At time of writing we're not sure how these can be utilized.

func (*Client) BadgeCompare

func (c *Client) BadgeCompare(displayName string) (*BadgeStatus, *BadgeStatus, error)

BadgeCompare will compare the earned badges of the currently authenticated user against displayName.

func (*Client) BadgeDetail

func (c *Client) BadgeDetail(badgeID int) (*Badge, error)

BadgeDetail will return details about a badge.

func (*Client) BadgeLeaderBoard

func (c *Client) BadgeLeaderBoard() ([]BadgeStatus, error)

BadgeLeaderBoard returns the leaderboard for points for the currently authenticated user.

func (*Client) BadgesAvailable

func (c *Client) BadgesAvailable() ([]Badge, error)

BadgesAvailable will return the list of badges not yet earned by the curently authenticated user.

func (*Client) BadgesEarned

func (c *Client) BadgesEarned() ([]Badge, error)

BadgesEarned will return the list of badges earned by the curently authenticated user.

func (*Client) BlockUser

func (c *Client) BlockUser(displayName string) error

BlockUser will block a user.

func (*Client) BlockedUsers

func (c *Client) BlockedUsers() ([]SocialProfile, error)

BlockedUsers returns the list of blocked users for the currently authenticated user.

func (*Client) CalendarMonth

func (c *Client) CalendarMonth(year int, month int) (*CalendarMonth, error)

CalendarMonth will get the activities for a given month

func (*Client) CalendarWeek

func (c *Client) CalendarWeek(year int, month int, week int) (*CalendarWeek, error)

CalendarWeek will get the activities for a given week. A week will be returned that contains the day requested, not starting with)

func (*Client) CalendarYear

func (c *Client) CalendarYear(year int) (*CalendarYear, error)

CalendarYear will get the activity summaries and list of days active for a given year

func (*Client) Connections

func (c *Client) Connections(displayName string) ([]SocialProfile, error)

Connections will list the connections of displayName. If displayName is empty, the current authenticated users connection list wil be returned.

func (*Client) DailyStress

func (c *Client) DailyStress(date time.Time) (*DailyStress, error)

DailyStress will retrieve stress levels for date.

func (*Client) DailySummaries

func (c *Client) DailySummaries(userID string, from time.Time, until time.Time) (*DailySummaries, error)

DailySummaries will retrieve a daily summary for userID.

func (*Client) DailySummary

func (c *Client) DailySummary(displayName string, date time.Time) (*DailySummary, error)

DailySummary will retrieve a detailed daily summary for date. If displayName is empty, the currently authenticated user will be used.

func (*Client) DeleteActivity

func (c *Client) DeleteActivity(id int) error

DeleteActivity will permanently delete an activity.

func (*Client) DeleteGoal

func (c *Client) DeleteGoal(displayName string, goalID int) error

DeleteGoal will delete an existing goal. If displayName is empty, the currently authenticated user will be used.

func (*Client) DeleteWeightin

func (c *Client) DeleteWeightin(date time.Time) error

DeleteWeightin will delete all biometric data for date.

func (*Client) Download

func (c *Client) Download(url string, w io.Writer) error

Download will retrieve a file from url using Garmin Connect credentials. It's mostly useful when developing new features or debugging existing ones. Please note that this will pass the Garmin session cookie to the URL provided. Only use this for endpoints on garmin.com.

func (*Client) ExportActivity

func (c *Client) ExportActivity(id int, w io.Writer, format ActivityFormat) error

ExportActivity will export an activity from Connect. The activity will be written til w.

func (*Client) Gear

func (c *Client) Gear(profileID int64) ([]Gear, error)

Gear will retrieve the details of the users gear

func (*Client) GearForActivity

func (c *Client) GearForActivity(profileID int64, activityID int) ([]Gear, error)

GearForActivity will retrieve the gear associated with an activity

func (c *Client) GearLink(uuid string, activityID int) error

GearLink will link an item of gear to an activity. Multiple items of gear can be linked.

func (*Client) GearStats

func (c *Client) GearStats(uuid string) (*GearStats, error)

GearStats will get the statistics of an item of gear, given the uuid

func (*Client) GearType

func (c *Client) GearType() ([]GearType, error)

GearType will list the gear types

func (c *Client) GearUnlink(uuid string, activityID int) error

GearUnlink will remove an item of gear from an activity. All items of gear can be unlinked.

func (*Client) Goals

func (c *Client) Goals(displayName string, goalType int) ([]Goal, error)

Goals lists all goals for displayName of type goalType. If displayName is empty, the currently authenticated user will be used.

func (*Client) Group

func (c *Client) Group(groupID int) (*Group, error)

Group returns details about groupID.

func (*Client) GroupAnnouncement

func (c *Client) GroupAnnouncement(groupID int) (*GroupAnnouncement, error)

GroupAnnouncement returns the announcement for groupID.

func (*Client) GroupMembers

func (c *Client) GroupMembers(groupID int) ([]GroupMember, error)

GroupMembers will return the member list of a group.

func (*Client) Groups

func (c *Client) Groups(displayName string) ([]Group, error)

Groups will return the group membership. If displayName is empty, the currently authenticated user will be used.

func (*Client) HistoricalAdhocChallenges

func (c *Client) HistoricalAdhocChallenges() ([]AdhocChallenge, error)

HistoricalAdhocChallenges will retrieve the list of completed ad-hoc challenges.

func (*Client) ImportActivity

func (c *Client) ImportActivity(file io.Reader, format ActivityFormat) (int, error)

ImportActivity will import an activity into Garmin Connect. The activity will be read from file.

func (*Client) JoinGroup

func (c *Client) JoinGroup(groupID int) error

JoinGroup joins a group. If profileID is 0, the currently authenticated user will be used.

func (*Client) LastUsed

func (c *Client) LastUsed(displayName string) (*LastUsed, error)

LastUsed will return information about the latest synchronization.

func (*Client) LatestWeight

func (c *Client) LatestWeight(date time.Time) (*Weightin, error)

LatestWeight will retrieve the latest weight by date.

func (*Client) LeaveAdhocChallenge

func (c *Client) LeaveAdhocChallenge(challengeUUID string, profileID int64) error

LeaveAdhocChallenge will leave an ad-hoc challenge. If profileID is 0, the currently authenticated user will be used.

func (*Client) LeaveGroup

func (c *Client) LeaveGroup(groupID int) error

LeaveGroup leaves a group.

func (*Client) LifetimeActivities

func (c *Client) LifetimeActivities(displayName string) (*LifetimeActivities, error)

LifetimeActivities will return some aggregated data about all activities.

func (*Client) LifetimeTotals

func (c *Client) LifetimeTotals(displayName string) (*LifetimeTotals, error)

LifetimeTotals returns some lifetime statistics for displayName.

func (*Client) PendingConnections

func (c *Client) PendingConnections() ([]SocialProfile, error)

PendingConnections returns a list of pending connections.

func (*Client) PersonalInformation

func (c *Client) PersonalInformation(displayName string) (*PersonalInformation, error)

PersonalInformation will retrieve personal information for displayName.

func (*Client) PublicSocialProfile

func (c *Client) PublicSocialProfile(displayName string) (*SocialProfile, error)

PublicSocialProfile retrieves the public profile for displayName.

func (*Client) RemoveConnection

func (c *Client) RemoveConnection(connectionRequestID int) error

RemoveConnection will remove a connection.

func (*Client) RenameActivity

func (c *Client) RenameActivity(activityID int, newName string) error

RenameActivity can be used to rename an activity.

func (*Client) RequestConnection

func (c *Client) RequestConnection(displayName string) error

RequestConnection will request a connection with displayName.

func (*Client) SearchConnections

func (c *Client) SearchConnections(keyword string) ([]SocialProfile, error)

SearchConnections can search other users of Garmin Connect.

func (*Client) SearchGroups

func (c *Client) SearchGroups(keyword string) ([]Group, error)

SearchGroups can search for groups in Garmin Connect.

func (*Client) SetOptions

func (c *Client) SetOptions(options ...Option)

SetOptions can be used to set various options on Client.

func (*Client) SetWeightGoal

func (c *Client) SetWeightGoal(goal int) error

SetWeightGoal will set a new weight goal.

func (*Client) Signout

func (c *Client) Signout() error

Signout will end the session with Garmin. If you use this for regular automated tasks, it would be nice to signout each time to avoid filling Garmin's session tables with a lot of short-lived sessions.

func (*Client) SleepData

func (c *Client) SleepData(displayName string, date time.Time) (*SleepSummary, []SleepMovement, []SleepLevel, error)

SleepData will retrieve sleep data for date for a given displayName. If displayName is empty, the currently authenticated user will be used.

func (*Client) SocialProfile

func (c *Client) SocialProfile(displayName string) (*SocialProfile, error)

SocialProfile retrieves a profile for a Garmin Connect user. If displayName is empty, the profile for the currently authenticated user will be returned.

func (*Client) Timezones

func (c *Client) Timezones() (Timezones, error)

Timezones will retrieve the list of known timezones in Garmin Connect.

func (*Client) UnblockUser

func (c *Client) UnblockUser(displayName string) error

UnblockUser removed displayName from the block list.

func (*Client) UpdateGoal

func (c *Client) UpdateGoal(displayName string, goal Goal) error

UpdateGoal will update an existing goal.

func (*Client) WeightByDate

func (c *Client) WeightByDate(date time.Time) (Time, float64, error)

WeightByDate retrieves the weight of date if available. If no weight data for date exists, it will return ErrNotFound.

func (*Client) WeightGoal

func (c *Client) WeightGoal(displayName string) (*Goal, error)

WeightGoal will list the users weight goal if any. If displayName is empty, the currently authenticated user will be used.

func (*Client) Weightins

func (c *Client) Weightins(startDate time.Time, endDate time.Time) (*WeightAverage, []Weightin, error)

Weightins will retrieve all weight ins between startDate and endDate. A summary is provided as well. This summary is calculated by Garmin Connect.

type DailyStress

type DailyStress struct {
	UserProfilePK int    `json:"userProfilePK"`
	CalendarDate  string `json:"calendarDate"`
	StartGMT      Time   `json:"startTimestampGMT"`
	EndGMT        Time   `json:"endTimestampGMT"`
	StartLocal    Time   `json:"startTimestampLocal"`
	EndLocal      Time   `json:"endTimestampLocal"`
	Max           int    `json:"maxStressLevel"`
	Average       int    `json:"avgStressLevel"`
	Values        []StressPoint
}

DailyStress is a stress reading for a single day.

type DailySummaries

type DailySummaries struct {
	Start                    time.Time   `json:"statisticsStartDate"`
	End                      time.Time   `json:"statisticsEndDate"`
	TotalSteps               []DateValue `json:"WELLNESS_TOTAL_STEPS"`
	ActiveCalories           []DateValue `json:"COMMON_ACTIVE_CALORIES"`
	FloorsAscended           []DateValue `json:"WELLNESS_FLOORS_ASCENDED"`
	IntensityMinutes         []DateValue `json:"WELLNESS_USER_INTENSITY_MINUTES_GOAL"`
	MaxHeartRate             []DateValue `json:"WELLNESS_MAX_HEART_RATE"`
	MinimumAverageHeartRate  []DateValue `json:"WELLNESS_MIN_AVG_HEART_RATE"`
	MinimumHeartrate         []DateValue `json:"WELLNESS_MIN_HEART_RATE"`
	AverageStress            []DateValue `json:"WELLNESS_AVERAGE_STRESS"`
	RestingHeartRate         []DateValue `json:"WELLNESS_RESTING_HEART_RATE"`
	MaxStress                []DateValue `json:"WELLNESS_MAX_STRESS"`
	AbnormalHeartRateAlers   []DateValue `json:"WELLNESS_ABNORMALHR_ALERTS_COUNT"`
	MaximumAverageHeartRate  []DateValue `json:"WELLNESS_MAX_AVG_HEART_RATE"`
	StepGoal                 []DateValue `json:"WELLNESS_TOTAL_STEP_GOAL"`
	FlorsAscendedGoal        []DateValue `json:"WELLNESS_USER_FLOORS_ASCENDED_GOAL"`
	ModerateIntensityMinutes []DateValue `json:"WELLNESS_MODERATE_INTENSITY_MINUTES"`
	TotalColaries            []DateValue `json:"WELLNESS_TOTAL_CALORIES"`
	BodyBatteryCharged       []DateValue `json:"WELLNESS_BODYBATTERY_CHARGED"`
	FloorsDescended          []DateValue `json:"WELLNESS_FLOORS_DESCENDED"`
	BMRCalories              []DateValue `json:"WELLNESS_BMR_CALORIES"`
	FoodCaloriesRemainin     []DateValue `json:"FOOD_CALORIES_REMAINING"`
	TotalCalories            []DateValue `json:"COMMON_TOTAL_CALORIES"`
	BodyBatteryDrained       []DateValue `json:"WELLNESS_BODYBATTERY_DRAINED"`
	AverageSteps             []DateValue `json:"WELLNESS_AVERAGE_STEPS"`
	VigorousIntensifyMinutes []DateValue `json:"WELLNESS_VIGOROUS_INTENSITY_MINUTES"`
	WellnessDistance         []DateValue `json:"WELLNESS_TOTAL_DISTANCE"`
	Distance                 []DateValue `json:"COMMON_TOTAL_DISTANCE"`
	WellnessActiveCalories   []DateValue `json:"WELLNESS_ACTIVE_CALORIES"`
}

DailySummaries provides a daily summary of various statistics for multiple days.

type DailySummary

type DailySummary struct {
	ProfileID                        int64         `json:"userProfileId"`
	TotalKilocalories                float64       `json:"totalKilocalories"`
	ActiveKilocalories               float64       `json:"activeKilocalories"`
	BMRKilocalories                  float64       `json:"bmrKilocalories"`
	WellnessKilocalories             float64       `json:"wellnessKilocalories"`
	BurnedKilocalories               float64       `json:"burnedKilocalories"`
	ConsumedKilocalories             float64       `json:"consumedKilocalories"`
	RemainingKilocalories            float64       `json:"remainingKilocalories"`
	TotalSteps                       int           `json:"totalSteps"`
	NetCalorieGoal                   float64       `json:"netCalorieGoal"`
	TotalDistanceMeters              int           `json:"totalDistanceMeters"`
	WellnessDistanceMeters           int           `json:"wellnessDistanceMeters"`
	WellnessActiveKilocalories       float64       `json:"wellnessActiveKilocalories"`
	NetRemainingKilocalories         float64       `json:"netRemainingKilocalories"`
	UserID                           int64         `json:"userDailySummaryId"`
	Date                             Date          `json:"calendarDate"`
	UUID                             string        `json:"uuid"`
	StepGoal                         int           `json:"dailyStepGoal"`
	StartTimeGMT                     Time          `json:"wellnessStartTimeGmt"`
	EndTimeGMT                       Time          `json:"wellnessEndTimeGmt"`
	StartLocal                       Time          `json:"wellnessStartTimeLocal"`
	EndLocal                         Time          `json:"wellnessEndTimeLocal"`
	Duration                         time.Duration `json:"durationInMilliseconds"`
	Description                      string        `json:"wellnessDescription"`
	HighlyActive                     time.Duration `json:"highlyActiveSeconds"`
	Active                           time.Duration `json:"activeSeconds"`
	Sedentary                        time.Duration `json:"sedentarySeconds"`
	Sleeping                         time.Duration `json:"sleepingSeconds"`
	IncludesWellnessData             bool          `json:"includesWellnessData"`
	IncludesActivityData             bool          `json:"includesActivityData"`
	IncludesCalorieConsumedData      bool          `json:"includesCalorieConsumedData"`
	PrivacyProtected                 bool          `json:"privacyProtected"`
	ModerateIntensity                time.Duration `json:"moderateIntensityMinutes"`
	VigorousIntensity                time.Duration `json:"vigorousIntensityMinutes"`
	FloorsAscendedInMeters           float64       `json:"floorsAscendedInMeters"`
	FloorsDescendedInMeters          float64       `json:"floorsDescendedInMeters"`
	FloorsAscended                   float64       `json:"floorsAscended"`
	FloorsDescended                  float64       `json:"floorsDescended"`
	IntensityGoal                    time.Duration `json:"intensityMinutesGoal"`
	FloorsAscendedGoal               int           `json:"userFloorsAscendedGoal"`
	MinHeartRate                     int           `json:"minHeartRate"`
	MaxHeartRate                     int           `json:"maxHeartRate"`
	RestingHeartRate                 int           `json:"restingHeartRate"`
	LastSevenDaysAvgRestingHeartRate int           `json:"lastSevenDaysAvgRestingHeartRate"`
	Source                           string        `json:"source"`
	AverageStress                    int           `json:"averageStressLevel"`
	MaxStress                        int           `json:"maxStressLevel"`
	Stress                           time.Duration `json:"stressDuration"`
	RestStress                       time.Duration `json:"restStressDuration"`
	ActivityStress                   time.Duration `json:"activityStressDuration"`
	UncategorizedStress              time.Duration `json:"uncategorizedStressDuration"`
	TotalStress                      time.Duration `json:"totalStressDuration"`
	LowStress                        time.Duration `json:"lowStressDuration"`
	MediumStress                     time.Duration `json:"mediumStressDuration"`
	HighStress                       time.Duration `json:"highStressDuration"`
	StressQualifier                  string        `json:"stressQualifier"`
	MeasurableAwake                  time.Duration `json:"measurableAwakeDuration"`
	MeasurableAsleep                 time.Duration `json:"measurableAsleepDuration"`
	LastSyncGMT                      Time          `json:"lastSyncTimestampGMT"`
	MinAverageHeartRate              int           `json:"minAvgHeartRate"`
	MaxAverageHeartRate              int           `json:"maxAvgHeartRate"`
}

DailySummary is an extensive summary for a single day.

type Date

type Date struct {
	Year       int
	Month      time.Month
	DayOfMonth int
}

Date represents a single day in Garmin Connect.

func ParseDate

func ParseDate(in string) (Date, error)

ParseDate will parse a date in the format yyyy-mm-dd.

func Today

func Today() Date

Today will return a Date set to today.

func (Date) MarshalJSON

func (d Date) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (Date) String

func (d Date) String() string

String implements Stringer.

func (Date) Time

func (d Date) Time() time.Time

Time returns a time.Time for usage in other packages.

func (*Date) UnmarshalJSON

func (d *Date) UnmarshalJSON(value []byte) error

UnmarshalJSON implements json.Unmarshaler.

type DateValue

type DateValue struct {
	Date  Date    `json:"calendarDate"`
	Value float64 `json:"value"`
}

DateValue is a numeric value recorded on a given date.

type Error

type Error string

Error is a type implementing the error interface. We use this to define constant errors.

func (Error) Error

func (e Error) Error() string

Error implements error.

type Gear

type Gear struct {
	Uuid            string  `json:"uuid"`
	GearPk          int     `json:"gearPk"`
	UserProfileID   int64   `json:"userProfilePk"`
	GearMakeName    string  `json:"gearMakeName"`
	GearModelName   string  `json:"gearModelName"`
	GearTypeName    string  `json:"gearTypeName"`
	DisplayName     string  `json:"displayName"`
	CustomMakeModel string  `json:"customMakeModel"`
	ImageNameLarge  string  `json:"imageNameLarge"`
	ImageNameMedium string  `json:"imageNameMedium"`
	ImageNameSmall  string  `json:"imageNameSmall"`
	DateBegin       Time    `json:"dateBegin"`
	DateEnd         Time    `json:"dateEnd"`
	MaximumMeters   float64 `json:"maximumMeters"`
	Notified        bool    `json:"notified"`
	CreateDate      Time    `json:"createDate"`
	UpdateDate      Time    `json:"updateDate"`
}

Gear describes a Garmin Connect gear entry

type GearStats

type GearStats struct {
	TotalDistance   float64 `json:"totalDistance"`
	TotalActivities int     `json:"totalActivities"`
	Processsing     bool    `json:"processing"`
}

GearStats describes the stats of gear

type GearType

type GearType struct {
	TypeID     int    `json:"gearTypePk"`
	TypeName   string `json:"gearTypeName"`
	CreateDate Time   `json:"createDate"`
	UpdateDate Time   `json:"updateData"`
}

GearType desribes the types of gear

type Goal

type Goal struct {
	ID           int64    `json:"id"`
	ProfileID    int64    `json:"userProfilePK"`
	GoalCategory int      `json:"userGoalCategoryPK"`
	GoalType     GoalType `json:"userGoalTypePK"`
	Start        Date     `json:"startDate"`
	End          Date     `json:"endDate,omitempty"`
	Value        int      `json:"goalValue"`
	Created      Date     `json:"createDate"`
}

Goal represents a fitness or health goal.

type GoalType

type GoalType int

GoalType represents different types of goals.

func (GoalType) String

func (t GoalType) String() string

String implements Stringer.

type Group

type Group struct {
	ID                    int            `json:"id"`
	Name                  string         `json:"groupName"`
	Description           string         `json:"groupDescription"`
	OwnerID               int            `json:"ownerId"`
	ProfileImageURLLarge  string         `json:"profileImageUrlLarge"`
	ProfileImageURLMedium string         `json:"profileImageUrlMedium"`
	ProfileImageURLSmall  string         `json:"profileImageUrlSmall"`
	Visibility            string         `json:"groupVisibility"`
	Privacy               string         `json:"groupPrivacy"`
	Location              string         `json:"location"`
	WebsiteURL            string         `json:"websiteUrl"`
	FacebookURL           string         `json:"facebookUrl"`
	TwitterURL            string         `json:"twitterUrl"`
	PrimaryActivities     []string       `json:"primaryActivities"`
	OtherPrimaryActivity  string         `json:"otherPrimaryActivity"`
	LeaderboardTypes      []string       `json:"leaderboardTypes"`
	FeatureTypes          []string       `json:"featureTypes"`
	CorporateWellness     bool           `json:"isCorporateWellness"`
	ActivityFeedTypes     []ActivityType `json:"activityFeedTypes"`
}

Group describes a Garmin Connect group.

type GroupAnnouncement

type GroupAnnouncement struct {
	ID               int    `json:"announcementId"`
	GroupID          int    `json:"groupId"`
	Title            string `json:"title"`
	Message          string `json:"message"`
	ExpireDate       Time   `json:"expireDate"`
	AnnouncementDate Time   `json:"announcementDate"`
}

GroupAnnouncement describes a group announcement. Only one announcement can exist per group.

type GroupMember

type GroupMember struct {
	SocialProfile

	Joined time.Time `json:"joinDate"`
	Role   string    `json:"groupRole"`
}

GroupMember describes a member of a group.

type LastUsed

type LastUsed struct {
	DeviceID             int    `json:"userDeviceId"`
	ProfileNumber        int    `json:"userProfileNumber"`
	ApplicationNumber    int    `json:"applicationNumber"`
	DeviceApplicationKey string `json:"lastUsedDeviceApplicationKey"`
	DeviceName           string `json:"lastUsedDeviceName"`
	DeviceUploadTime     Time   `json:"lastUsedDeviceUploadTime"`
	ImageURL             string `json:"imageUrl"`
	Released             bool   `json:"released"`
}

LastUsed describes the last synchronization.

type LifetimeActivities

type LifetimeActivities struct {
	Activities    int     `json:"totalActivities"`    // The number of activities
	Distance      float64 `json:"totalDistance"`      // The total distance in meters
	Duration      float64 `json:"totalDuration"`      // The duration of all activities in seconds
	Calories      float64 `json:"totalCalories"`      // Energy in C
	ElevationGain float64 `json:"totalElevationGain"` // Total elevation gain in meters
}

LifetimeActivities is describing a basic summary of all activities.

type LifetimeTotals

type LifetimeTotals struct {
	ProfileID      int     `json:"userProfileId"`
	ActiveDays     int     `json:"totalActiveDays"`
	Calories       float64 `json:"totalCalories"`
	Distance       int     `json:"totalDistance"`
	GoalsMetInDays int     `json:"totalGoalsMetInDays"`
	Steps          int     `json:"totalSteps"`
}

LifetimeTotals is ligetime statistics for the Connect user.

type Logger

type Logger interface {
	Printf(format string, v ...interface{})
}

Logger defines the interface understood by the Connect client for logging.

type Option

type Option func(*Client)

Option is the type to set options on the client.

func AutoRenewSession

func AutoRenewSession(autoRenew bool) Option

AutoRenewSession will set if the session should be autorenewed upon expire. Default is true.

func Credentials

func Credentials(email string, password string) Option

Credentials can be used to pass login credentials to NewClient.

func DebugLogger

func DebugLogger(logger Logger) Option

DebugLogger is used to set a debug logger.

func DumpWriter

func DumpWriter(w io.Writer) Option

DumpWriter will instruct Client to dump all HTTP requests and responses to and from Garmin to w.

func LoadBalancerID

func LoadBalancerID(loadBalancerID string) Option

LoadBalancerID will set a load balancer ID. This is used by Garmin load balancers to route subsequent requests to the same backend server.

func SessionID

func SessionID(sessionID string) Option

SessionID will set a predefined session ID. This can be useful for clients keeping state. A few HTTP roundtrips can be saved, if the session ID is reused. And some load would be taken of Garmin servers. This must be accompanied by LoadBalancerID. Generally this should not be used. Users of this package should save all exported fields from Client and re-use those at a later request. json.Marshal() and json.Unmarshal() can be used.

type PersonalInformation

type PersonalInformation struct {
	UserInfo         UserInfo         `json:"userInfo"`
	BiometricProfile BiometricProfile `json:"biometricProfile"`
}

PersonalInformation is user info and a biometric profile for a user.

type Player

type Player struct {
	UserProfileID         int     `json:"userProfileId"`
	TotalNumber           float64 `json:"totalNumber"`
	LastSyncTime          Time    `json:"lastSyncTime"`
	Ranking               int     `json:"ranking"`
	ProfileImageURLSmall  string  `json:"profileImageSmall"`
	ProfileImageURLMedium string  `json:"profileImageMedium"`
	FullName              string  `json:"fullName"`
	DisplayName           string  `json:"displayName"`
	ProUser               bool    `json:"isProUser"`
	TodayNumber           float64 `json:"todayNumber"`
	AcceptedChallenge     bool    `json:"isAcceptedChallenge"`
}

Player represents a participant in a challenge.

type SleepLevel

type SleepLevel struct {
	Start Time       `json:"startGMT"`
	End   Time       `json:"endGMT"`
	State SleepState `json:"activityLevel"`
}

SleepLevel represents the sleep level for a longer period of time.

type SleepMovement

type SleepMovement struct {
	Start Time    `json:"startGMT"`
	End   Time    `json:"endGMT"`
	Level float64 `json:"activityLevel"`
}

SleepMovement denotes the amount of movement for a short time period during sleep.

type SleepState

type SleepState int

SleepState is used to describe the state of sleep with a device capable of measuring sleep health.

const (
	SleepStateUnknown SleepState = -1
	SleepStateDeep    SleepState = 0
	SleepStateLight   SleepState = 1
	SleepStateREM     SleepState = 2
	SleepStateAwake   SleepState = 3
)

Known sleep states in Garmin Connect.

func (SleepState) String

func (s SleepState) String() string

Sleep implements fmt.Stringer.

func (*SleepState) UnmarshalJSON

func (s *SleepState) UnmarshalJSON(value []byte) error

UnmarshalJSON implements json.Unmarshaler.

type SleepSummary

type SleepSummary struct {
	ID               int64         `json:"id"`
	UserProfilePK    int64         `json:"userProfilePK"`
	Sleep            time.Duration `json:"sleepTimeSeconds"`
	Nap              time.Duration `json:"napTimeSeconds"`
	Confirmed        bool          `json:"sleepWindowConfirmed"`
	Confirmation     string        `json:"sleepWindowConfirmationType"`
	StartGMT         Time          `json:"sleepStartTimestampGMT"`
	EndGMT           Time          `json:"sleepEndTimestampGMT"`
	StartLocal       Time          `json:"sleepStartTimestampLocal"`
	EndLocal         Time          `json:"sleepEndTimestampLocal"`
	AutoStartGMT     Time          `json:"autoSleepStartTimestampGMT"`
	AutoEndGMT       Time          `json:"autoSleepEndTimestampGMT"`
	Unmeasurable     time.Duration `json:"unmeasurableSleepSeconds"`
	Deep             time.Duration `json:"deepSleepSeconds"`
	Light            time.Duration `json:"lightSleepSeconds"`
	REM              time.Duration `json:"remSleepSeconds"`
	Awake            time.Duration `json:"awakeSleepSeconds"`
	DeviceRemCapable bool          `json:"deviceRemCapable"`
	REMData          bool          `json:"remData"`
}

SleepSummary is a summary of sleep for a single night.

type SocialProfile

type SocialProfile struct {
	ID                    int64    `json:"id"`
	ProfileID             int64    `json:"profileId"`
	ConnectionRequestID   int      `json:"connectionRequestId"`
	GarminGUID            string   `json:"garminGUID"`
	DisplayName           string   `json:"displayName"`
	Fullname              string   `json:"fullName"`
	Username              string   `json:"userName"`
	ProfileImageURLLarge  string   `json:"profileImageUrlLarge"`
	ProfileImageURLMedium string   `json:"profileImageUrlMedium"`
	ProfileImageURLSmall  string   `json:"profileImageUrlSmall"`
	Location              string   `json:"location"`
	FavoriteActivityTypes []string `json:"favoriteActivityTypes"`
	UserRoles             []string `json:"userRoles"`
	UserProfileFullName   string   `json:"userProfileFullName"`
	UserLevel             int      `json:"userLevel"`
	UserPoint             int      `json:"userPoint"`
}

SocialProfile represents a Garmin Connect user.

type StressPoint

type StressPoint struct {
	Timestamp time.Time
	Value     int
}

StressPoint is a measured stress level at a point in time.

type Time

type Time struct{ time.Time }

Time is a type masking a time.Time capable of parsing the JSON from Garmin Connect.

func (*Time) MarshalJSON

func (t *Time) MarshalJSON() ([]byte, error)

MarshalJSON implements json.Marshaler.

func (*Time) UnmarshalJSON

func (t *Time) UnmarshalJSON(value []byte) error

UnmarshalJSON implements json.Unmarshaler. It can parse timestamps returned from connect.garmin.com.

type Timezone

type Timezone struct {
	ID        int     `json:"unitId"`
	Key       string  `json:"unitKey"`
	GMTOffset float64 `json:"gmtOffset"`
	DSTOffset float64 `json:"dstOffset"`
	Group     int     `json:"groupNumber"`
	TimeZone  string  `json:"timeZone"`
}

Timezone represents a timezone in Garmin Connect.

func (*Timezone) Location

func (t *Timezone) Location() (*time.Location, error)

Location will (try to) return a location for use with time.Time functions.

type Timezones

type Timezones []Timezone

Timezones is the list of known time zones in Garmin Connect.

func (Timezones) FindID

func (ts Timezones) FindID(id int) (Timezone, bool)

FindID will search for the timezone with id.

func (Timezones) FindKey

func (ts Timezones) FindKey(key string) (Timezone, bool)

FindKey will search for the timezone with key key.

type UserInfo

type UserInfo struct {
	Gender   string `json:"genderType"`
	Email    string `json:"email"`
	Locale   string `json:"locale"`
	TimeZone string `json:"timezone"`
	Age      int    `json:"age"`
}

UserInfo is very basic information about a user.

type WeightAverage

type WeightAverage struct {
	Weightin
	From  int `json:"from"`
	Until int `json:"until"`
}

WeightAverage is aggregated weight data for a specific period.

type Weightin

type Weightin struct {
	Date              Date    `json:"date"`
	Version           int     `json:"version"`
	Weight            float64 `json:"weight"`     // gram
	BMI               float64 `json:"bmi"`        // weight / height²
	BodyFatPercentage float64 `json:"bodyFat"`    // percent
	BodyWater         float64 `json:"bodyWater"`  // kilogram
	BoneMass          int     `json:"boneMass"`   // gram
	MuscleMass        int     `json:"muscleMass"` // gram
	SourceType        string  `json:"sourceType"`
}

Weightin is a single weight event.

type YearItem

type YearItem struct {
	Date    Date `json:"date"`
	Display int  `json:"display"`
}

YearItem describes an item on a Garmin Connect calendar year

type YearSummary

type YearSummary struct {
	ActivityTypeID     int `json:"activityTypeId"`
	NumberOfActivities int `json:"numberOfActivities"`
	TotalDistance      int `json:"totalDistance"`
	TotalDuration      int `json:"totalDuration"`
	TotalCalories      int `json:"totalCalories"`
}

YearSummary describes a per-activity-type yearly summary on a Garmin Connect calendar year

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL