withings

package module
v1.3.1 Latest Latest
Warning

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

Go to latest
Published: Feb 12, 2022 License: MIT Imports: 20 Imported by: 2

README

Go client for the Withings API

This is a go client that allows easy access to the Withings API and as of v2 supports the required Oauth2. More documentation regarding the Withings API can be found here. More detailed documentation of the client can be found in the godocs.

v1 to v2 Changes

Nokia changed the API to allow Oauth2 while removing Oauth1 as an option. Due to this change, the client API has changed when it comes to handling authentication and tokens. For the most part the changes make things easier but they are breaking changes. The good new is there is no longer a dependency on the forked Ouath1 implementation.

Supported Resources

  • User Access Requests
  • Retrieving user body measurements
  • Retrieve activity measurements
  • Retrieve workouts
  • Retrieve intraday activities - Apparently requires additional authorization which I don't have yet so no testing.
  • Retrieve sleep measures - Limited testing so report any issues.
  • Retrieve sleep summary - Limited testing so report any issues.
  • Creating a notification
  • Retrieving a single notification
  • Retrieving all notifications for a user
  • Revoke notifications

Installation

go get github.com/asymmetricia/withings

Highlevel Usage Overview

It's best if you read up on Oauth2 if you are not familiar but the client should be simple enough to get working without understanding how Oauth2 works.

New User
  • Create a withings account and register your app.
  • Create a client and perform the tasks to get the token/user struct.
    • Send user to Oauth2 authorization URL.
    • Catch the redirect back via a server or manually pulling the "code" from the path.
    • Generate a user.
  • Execute queries!
Returning User
  • Create client (Assuming you have an account otherwise the user couldn't be returning...)
  • Generate user from stored token.
  • Execute queries!

Highlevel Usage Example

New User

1. Obtain your ClientID and ClientSecret 2. Create a new client

clientID := "id"
clientSecrete := "secret"
clientRedirectURL := "url" // This is the URL Withings will redirect the client to
                           // after they authorized your application. This is
                           // the same URL you provided when you registered your
                           // application with Withings.
                           // For any real world use you will need to have a
                           // http server running and listening on that URL
                           // so you can obtain the code that is retruned.
                           // For simple testing you can just manually navigate
                           // to the URL that will be generated and copy the
                           // code.

client := withings.NewClient(clientID, clientSecret, clientRedirectURL)

3. Generate the authorization URL.

authURL, _, err := client.AuthCodeURL() // Ignoring the state (second return)
                                        // in this example but in realworld use
                                        // you will want to record this to
                                        // compare to the state value returned
                                        // by the redirect from Withings to
                                        // verify its a redirect from your
                                        // request.
                                        // The state is auto generated for you
                                        // using cyrto/rand but the random
                                        // generation can be replaced with your
                                        // own function if you would like.

4. User navigates to URL and the code and state are retrieved. 5. Create new user using returned code.

u, err := client.NewUserFromAuthCode(context.Background(), code) // Obviously
                                        // use whatever context you would like
                                        // here.

// You should store the Access Token, Expiry, and Refresh Token values from
// u.OauthToken. These are used to obtain a new user object later (see below).
// You can obtain a user with _just_ the Refresh Token but Withings has rate
// limits on this.

if err != nil {
    panic(err) // Handle the error however is appropriate for your code.
}

6. DONE - you now have a user that can make data requests.

Returning User

1. Create a new client

clientID := "id"
clientSecrete := "secret"
clientRedirectURL := "url" // This is the URL Withings will redirect the client to
                           // after they authorized your application. This is
                           // the same URL you provided when you registered your
                           // application with Withings.
                           // For any real world use you will need to have a
                           // http server running and listening on that URL
                           // so you can obtain the code that is returned.
                           // For simple testing you can just manually navigate
                           // to the URL that will be generated and copy the
                           // code.

client := withings.NewClient(clientID, clientSecret, clientRedirectURL)

2. Generate a new user from the stored tokens.


// This creates a new user based on the tokens provided. The given access token
// will continue to be used as long as expiry is in the future, after which
// refresh token will be used to fetch a new set of tokens.

// Note that after calling even just this function, the tokens may change,
// including the refresh token; and you should store the updated token, if they
// do change.

u, err := client.NewUserFromRefreshToken(context.Background(), accessToken, expiry, refreshToken)

3. DONE - you now have a user that can make data requests.

Making Requests

Requests are performed from methods on the User. Each request accepts a specific query struct with the details for the request. For example:

p := withings.BodyMeasuresQueryParams{}

t := time.Now().AddDate(0, 0, -14)
p.StartDate = &t

m, err := u.GetBodyMeasures(&p)

Note about Tokens: After any request to Withings, the user's OauthToken object might change. If the values do change (especially RefreshToken), then you need to persist the new token values, otherwise you will no longer have access to the user.

In most cases the response will contain all the information you need. Some methods provide additional optional processing that can provide a more usable form to the data. GetBodyMeasures is one of these methods. It's recommended to read the docs for each method to see how best to use them.

measures := m.ParseData()

Making context Requests

Every request method has a partner method ending with Ctx that takes a context that will be used for the HTTP call. This allows you to provide a custom context if you desire.

p := withings.BodyMeasuresQueryParams{}

t := time.Now().AddDate(0, 0, -14)
p.StartDate = &t

m, err := u.GetBodyMeasuresCtx(context.Background(), &p)

History

Documentation

Overview

Package withings is a client module for working with the Withings (previously Nokia Health (previously Withings)) API. The current version (v2) of this module has been updated to work with the newer Oauth2 implementation of the API.

Authorization Overview

As with all Oauth2 APIs, you must obtain authorization to access the users data. To do so you must first register your application with the Withings api to obtain a ClientID and ClientSecret.

http://developer.withings.com/oauth2/#tag/introduction

Once you have your client information you can now create a new client. You will need to also provide the redirectURL you provided during application registration. This URL is where the user will be redirected to and will include the code you need to generate the accessToken needed to access the users data. Under normal situations you should have an http server listening on that address and pull the code from the URL query parameters.

client := withings.NewClient(clientID, clientSecret, clientRedirectURL)

You can now use the client to generate the authorization URL the user needs to navigate to. This URL will take the user to a page that will prompt them to allow your application to access their data. The state string returned by the method is a randomly generated BASE64 string using the crypto/rand module. It will be returned in the redirect as a query parameter and the two values verified they match. It's not required, but useful for security reasons.

authURL, state, err := client.AuthCodeURL()

Using the code returned by the redirect in the query parameters, you can generate a new user. This user struct can be used to immediately perform actions against the users data. It also contains the token you should save somewhere for reuse. Obviously use whatever context you would like here.

u, err := client.NewUserFromAuthCode(context.Background(), code)

Make sure the save at least the refreshToken for accessing the user data at a later date. You may also save the accessToken, but it does expire and creating a new client from saved token data only requires the refreshToken.

refreshToken, err := i := u.Token.Token().RefreshToken

Creating User From Saved Token

You can easily create a user from a saved token using the NewUserFromRefreshToken method. A working configured client is required for the user generated from this method to work.

Requesting Data

The user struct has various methods associated with each API endpoint to perform data retrieval. The methods take a specific param struct specifying the api options to use on the request. The API is a bit "special" so the params vary a bit between each method. The client does what it can to smooth those out but there is only so much that can be done.

startDate := time.Now().AddDate(0, 0, -2)
endDate := time.Now()

p := BodyMeasureQueryParams {
	StartDate: &startDate,
	EndDate: &endDate,
}
m, err := u.GetBodyMeasures(&p)

Context Usage

Every method has two forms, one that accepts a context and one that does now. This allows you to provide a context on each request if you would like to.

startDate := time.Now().AddDate(0, 0, -2)
endDate := time.Now()

p := BodyMeasureQueryParams {
	StartDate: &startDate,
	EndDate: &endDate,
}
m, err := u.GetBodyMeasures(&p)

Request Timeout

By default all methods utilize a context to timeout the request to the API. The value of the timeout is stored on the Client and can be access as/set on Client.Timeout. Setting is _not_ thread safe and should only be set on client creation. If you need to change the timeout for different requests use the methodCtx variant of the method.

Oauth2 State Randomization

By default the state generated by the AuthCodeURL utilized crypto/rand. If you would like to implement your own random method you can do so by assigning the function to Rand field of the Client struct. The function should support the Rand type. Also this is _not_ thread safe so only perform this action on client creation.

Raw Request Data

By default every returned response will be parsed and the parsed data returned. If you need access to the raw request data you can enable it by setting the SaveRawResponse field of the client struct to true. This should be done at client creation time. With it set to true the RawResponse field of the returned structs will include the raw response.

Data Helper Methods

Some data request methods include a parseResponse field on the params struct. If this is included additional parsing is performed to make the data more usable. This can be seen on GetBodyMeasures for example.

Include Path Fields In Response

You can include the path fields sent to the API by setting IncludePath to true on the client. This is primarily used for debugging but could be helpful in some situations.

Oauth2 Scopes

By default the client will request all known scopes. If you would like to pair down this you can change the scope by using the SetScope method of the client. Consts in the form of ScopeXxx are provided to aid selection.

Index

Constants

This section is empty.

Variables

View Source
var Oauth2Endpoint = oauth2.Endpoint{
	AuthURL:  "https://account.withings.com/oauth2_user/authorize2",
	TokenURL: "https://wbsapi.withings.net/v2/oauth2",
}

Endpoint is Withing's OAuth 2.0 endpoint.

Functions

func GetFieldName

func GetFieldName(s interface{}, name string) string

GetFieldName returns the json filed name for the field if one is found. If one is not found it will return an empty string.

Types

type ActivitiesMeasuresResp

type ActivitiesMeasuresResp struct {
	Status      status.Status               `json:"status"`
	Error       string                      `json:"error"`
	Body        *ActivitiesMeasuresRespBody `json:"body"`
	RawResponse []byte
	Path        string
}

ActivitiesMeasuresResp contains the unmarshalled response from the api. If the client has been set to include raw respeonse the RawResponse byte slice will be populated with raw bytes returned by the API.

type ActivitiesMeasuresRespBody

type ActivitiesMeasuresRespBody struct {
	ParsedDate  *time.Time `json:"parseddate"`
	Date        *string    `json:"date"`
	Steps       *float64   `json:"steps"`
	Distance    *float64   `json:"distance"`
	Calories    *float64   `json:"calories"`
	Elevation   *float64   `json:"elevation"`
	Soft        *int       `json:"soft"`
	Moderate    *int       `json:"moderate"`
	Intense     *int       `json:"intense"`
	TimeZone    *string    `json:"timezone"`
	Activities  []Activity `json:"activity"`
	More        bool       `json:"more"`
	Offset      int        `json:"offset"`
	SingleValue bool       `json:"singleValue"`
}

ActivitiesMeasuresRespBody contains the response body as provided by the api. The Withings API includes single values responses directly in the body. As such they are all pointers. You may check SingleValue to determine if a single value was provided.

type Activity

type Activity struct {
	ParsedDate *time.Time `json:"parseddate"`
	Date       string     `json:"date"`
	Steps      float64    `json:"steps"`
	Distance   float64    `json:"distance"`
	Calories   float64    `json:"calories"`
	Elevation  float64    `json:"elevation"`
	Soft       int        `json:"soft"`
	Moderate   int        `json:"moderate"`
	Intense    int        `json:"intense"`
	TimeZone   string     `json:"timezone"`
}

Activity represents an activity as recorded by Withings.

type ActivityMeasuresQueryParam

type ActivityMeasuresQueryParam struct {
	UserID int `json:"userid"`
	// Date             *time.Time `json:"date"`
	StartDateYMD     *time.Time `json:"startdateymd"`
	EndDateYMD       *time.Time `json:"enddateymd"`
	LasteUpdate      *time.Time `json:"lastupdate"`
	Offset           *int       `json:"offset"`
	DisableDateParse bool       `json:"diabledateparse"`
}

ActivityMeasuresQueryParam acts as the config parameter for activity measurement queries. All options feilds can be set to null but at least one of the date fields need to be specified or the API will fail. Additionally there is no ParseResponse option as there is no need to because the activities response doesn't need further parsing.

type BodyMeasureGroupResp

type BodyMeasureGroupResp struct {
	GrpID    int                   `json:"grpid"`
	Attrib   int                   `json:"attrib"`
	Date     int64                 `json:"date"`
	Category int                   `json:"category"`
	Measures []BodyMeasuresMeasure `json:"measures"`
}

BodyMeasureGroupResp is a single body measurment group as found in the resposne. Each group has a set of measures that can then be parsed manually or via the Parse method on BodyMeasuresQueryParams.

type BodyMeasureRespBody

type BodyMeasureRespBody struct {
	Updatetime  int64                  `json:"updatetime"`
	More        int                    `json:"more"`
	Timezone    string                 `json:"timezone"`
	MeasureGrps []BodyMeasureGroupResp `json:"measuregrps"`
}

BodyMeasureRespBody represents the body portion of the body measure response. The body portion is not required and thus this may not be found in the response object.

type BodyMeasures

type BodyMeasures struct {
	Weights                 []Weight
	Heights                 []Height
	FatFreeMass             []FatFreeMass
	FatRatios               []FatRatio
	FatMassWeights          []FatMassWeight
	DiastolicBloodPressures []DiastolicBloodPressure
	SystolicBloodPressures  []SystolicBloodPressure
	HeartPulses             []HeartPulse
	Temperatures            []Temperature
	SP02Percents            []SP02Percent
	BodyTemperatures        []BodyTemperature
	SkinTemperatures        []SkinTemperature
	MuscleMasses            []MuscleMass
	Hydration               []Hydration
	BoneMasses              []BoneMass
	PulseWaveVelocity       []PulseWaveVelocity
}

type BodyMeasuresMeasure

type BodyMeasuresMeasure struct {
	Value int               `json:"value"`
	Type  meastype.MeasType `json:"type"`
	Unit  int               `json:"unit"`
}

BodyMeasuresMeasure is a single body measure found in the response.

type BodyMeasuresQueryParams

type BodyMeasuresQueryParams struct {
	UserID        int                `json:"userid"`
	StartDate     *time.Time         `json:"startdate"`
	EndDate       *time.Time         `json:"enddate"`
	LastUpdate    *time.Time         `json:"lastupdate"`
	DevType       *devtype.DevType   `json:"devtype"`
	MeasType      *meastype.MeasType `json:"meastype"`
	Category      *int               `json:"category"`
	Limit         *int               `json:"limit"`
	Offset        *int               `json:"offset"`
	ParseResponse bool
}

BodyMeasuresQueryParams acts as the config parameter for body measurement queries. All optional field can be set to null. The ParsedResponse can be set to true and the request will automatically parse the response into easy to use structs. Otherwise this can be done manually when needed via the Parse method.

type BodyMeasuresResp

type BodyMeasuresResp struct {
	Status         status.Status        `json:"status"`
	Body           *BodyMeasureRespBody `json:"body"`
	RawResponse    []byte
	Path           string
	ParsedResponse *BodyMeasures
	Error          string
}

BodyMeasuresResp contains the unmarshalled response from the api. If the client has been set to include raw respeonse the RawResponse byte slice will be populated with raw bytes returned by the API.

func (BodyMeasuresResp) ParseData

func (rm BodyMeasuresResp) ParseData() *BodyMeasures

ParseData parses all the data provided into buckets of each type of measurement. It also performs the nessasary date and unit conversion.

type BodyTemperature

type BodyTemperature struct {
	Date     time.Time
	Celcius  float64
	Attrib   int
	Category int
}

type BoneMass

type BoneMass struct {
	Date     time.Time
	Mass     float64
	Attrib   int
	Category int
}

type Client

type Client struct {
	OAuth2Config    *oauth2.Config
	SaveRawResponse bool
	IncludePath     bool
	Rand            Rand
	Timeout         time.Duration
}

Client contains all the required information to interact with the Withings API.

func NewClient

func NewClient(clientID string, clientSecret string, redirectURL string) Client

NewClient creates a new client using the Ouath2 information provided. The required parameters can be obtained when developers register with Withings to use the API.

func (*Client) AuthCodeURL

func (c *Client) AuthCodeURL() (url string, state string, err error)

AuthCodeURL generates the URL user authorization URL. Users should be redirected to this URL so they can allow your application. They will then be directed back to the redirectURL provided when the client was created. This redirection will contain the authentication code needed to generate an access token.

The state parameter of the request is generated using crypto/rand and returned as state. The random generation function can be replaced by assigning a new function to Client.Rand.

func (*Client) GenerateAccessToken

func (c *Client) GenerateAccessToken(ctx context.Context, code string) (*oauth2.Token, error)

GenerateAccessToken generates the access token from the authorization code. The authorization code is the one provided in the parameters of the redirect request from the URL generated by AuthCodeURL. Generally this isn't directly called and create user is used instead. The state is also not validated and is left for the calling methods.

func (*Client) NewUserFromAccessToken added in v1.2.0

func (c *Client) NewUserFromAccessToken(ctx context.Context, accessToken string, tokenExpiry time.Time, refreshToken string) (*User, error)

NewUserFromAccessToken returns a user with the given access token. If it's expired, refreshToken is used to retrieve a refresh token. The resulting user may have a different refresh token, and this should be checked and recorded if it changes.

func (*Client) NewUserFromAuthCode

func (c *Client) NewUserFromAuthCode(ctx context.Context, code string) (*User, error)

NewUserFromAuthCode generates a new user by requesting the token using the authentication code provided. This is generally only used after a user has just authorized access and the client is processing the redirect.

func (*Client) NewUserFromRefreshToken

func (c *Client) NewUserFromRefreshToken(ctx context.Context, refreshToken string) (*User, error)

NewUserFromRefreshToken generates a new user that the refresh token is for. At time of first use, a new access token will be retrieved. The user may end up with a different refresh token, and this should be checked and recorded if it changes.

func (*Client) SetScope

func (c *Client) SetScope(scopes ...string)

SetScope allows for setting the scope of the client which is used during authorization requests for new users. By default the scope will be all scopes. This is also not thread safe.

type CreateNotificationParam

type CreateNotificationParam struct {
	CallbackURL url.URL `json:"callbackurl"`
	Comment     string  `json:"comment"`
	Appli       int     `json:"appli"`
}

CreateNotificationParam provides the query parameters nessasary to create a notication via the Withings API.

type CreateNotificationResp

type CreateNotificationResp struct {
	Status      status.Status `json:"status"`
	Error       string        `json:"error"`
	RawResponse []byte
	Path        string
}

CreateNotificationResp provides the response of the create request.

type DiastolicBloodPressure

type DiastolicBloodPressure struct {
	Date     time.Time
	MmHg     float64
	Attrib   int
	Category int
}

type FatFreeMass

type FatFreeMass struct {
	Date     time.Time
	Kgs      float64
	Attrib   int
	Category int
}

type FatMassWeight

type FatMassWeight struct {
	Date     time.Time
	Kgs      float64
	Attrib   int
	Category int
}

type FatRatio

type FatRatio struct {
	Date     time.Time
	Ratio    float64
	Attrib   int
	Category int
}

type HeartPulse

type HeartPulse struct {
	Date     time.Time
	BPM      float64
	Attrib   int
	Category int
}

type Height

type Height struct {
	Date     time.Time
	Meters   float64
	Attrib   int
	Category int
}

type Hydration

type Hydration struct {
	Date      time.Time
	Hydration float64
	Attrib    int
	Category  int
}

type IntraDayActivity

type IntraDayActivity struct {
	Calories  *float64 `json:"calories"`
	Distance  *float64 `json:"distance"`
	Duration  *int     `json:"duration"`
	Elevation *float64 `json:"elevation"`
	Steps     *int     `json:"steps"`
	PoolLap   *int     `json:"pool_lap"`
}

IntraDayActivity represents an intra day activity as returned by the API. Their is likey work to be done here as the documentation does not provide musch information reegarding what paramters it should contain.

type IntradayActivityQueryParam

type IntradayActivityQueryParam struct {
	UserID    int        `json:"userid"`
	StartDate *time.Time `json:"startdate"`
	EndDate   *time.Time `json:"enddate"`
}

IntradayActivityQueryParam acts as the config parameter for intraday activity retrieval requests.

type IntradayActivityResp

type IntradayActivityResp struct {
	Status      status.Status             `json:"status"`
	Error       string                    `json:"error"`
	Body        *IntradayActivityRespBody `json:"body"`
	RawResponse []byte
	Path        string
}

IntradayActivityResp represents the unmarshelled api response for intraday activities.

type IntradayActivityRespBody

type IntradayActivityRespBody struct {
	Series map[int64]IntraDayActivity `json:"series"`
}

IntradayActivityRespBody represents the unmarshelled api response body for intraday activities.

type ListNotificationsParam

type ListNotificationsParam struct {
	Appli *int `json:"appli"`
}

ListNotificationsParam provides the query parameters nessasary to list all the notifications configured for the user.

type ListNotificationsResp

type ListNotificationsResp struct {
	Status      status.Status              `json:"status"`
	Body        *ListNotificationsRespBody `json:"body"`
	RawResponse []byte
	Path        string
	Error       string
}

ListNotificationsResp represents the unmarshelled api response for listing notifications.

type ListNotificationsRespBody

type ListNotificationsRespBody struct {
	Profiles []NotificationProfile `json:"profiles"`
}

ListNotificationsRespBody represents the notification list body.

type MuscleMass

type MuscleMass struct {
	Date     time.Time
	Mass     float64
	Attrib   int
	Category int
}

type NotificationInfoParam

type NotificationInfoParam struct {
	CallbackURL url.URL `json:"callbackurl"`
	Appli       *int    `json:"appli"`
}

NotificationInfoParam provides the query parameters nessasary to retrieve information about a specific notification.

type NotificationInfoResp

type NotificationInfoResp struct {
	Status      status.Status             `json:"status"`
	Body        *NotificationInfoRespBody `json:"body"`
	RawResponse []byte
	Path        string
	Error       string
}

NotificationInfoResp represents the unmarshelled api reponse for viewing a single notification.

type NotificationInfoRespBody

type NotificationInfoRespBody struct {
	Expires       int64      `json:"expires"`
	Comment       string     `json:"comment"`
	ExpiresParsed *time.Time `json:"expiresparsed"`
}

NotificationInfoRespBody represents the body of the notification response.

type NotificationProfile

type NotificationProfile struct {
	Expires       int64      `json:"expires"`
	Comment       string     `json:"comment"`
	ExpiresParsed *time.Time `json:"expiresparsed"`
}

NotificationProfile is a notification profile for the user.

type PulseWaveVelocity

type PulseWaveVelocity struct {
	Date     time.Time
	Velocity float64
	Attrib   int
	Category int
}

type Rand

type Rand func() (string, error)

Rand provides a function type to allow passing in custom random functions used for state generation.

type RevokeNotificationParam

type RevokeNotificationParam struct {
	CallbackURL url.URL `json:"callbackurl"`
	Appli       *int    `json:"appli"`
}

RevokeNotificationParam provides the query parameters nessasry to revoke a notification.

type RevokeNotificationResp

type RevokeNotificationResp struct {
	Status      status.Status `json:"status"`
	RawResponse []byte
	Path        string
	Error       string
}

RevokeNotificationResp is the response from trying to revoke a notification.

type SP02Percent

type SP02Percent struct {
	Date       time.Time
	Percentage float64
	Attrib     int
	Category   int
}

type Scope

type Scope string

Scope defines the types of scopes accepted by the API.

const (
	// ScopeUserMetrics provides access to the Getmeas actions.
	ScopeUserMetrics Scope = "user.metrics"
	// ScopeUserInfo provides access to the user information.
	ScopeUserInfo Scope = "user.info"
	// ScopeUserActivity provides access to the users activity data.
	ScopeUserActivity Scope = "user.activity"
)

type SkinTemperature

type SkinTemperature struct {
	Date     time.Time
	Celcius  float64
	Attrib   int
	Category int
}

type SleepMeasure

type SleepMeasure struct {
	StartDate       int64                 `json:"startdate"`
	EndDate         int64                 `json:"enddate"`
	State           sleepstate.SleepState `json:"state"`
	StartDateParsed *time.Time            `json:"startdateparsed"`
	EndDateParsed   *time.Time            `'json:"enddateparsed"`
}

SleepMeasure is a specific instance of sleep returned by the API.

type SleepMeasuresQueryParam

type SleepMeasuresQueryParam struct {
	UserID    int       `json:"userid"`
	StartDate time.Time `json:"startdate"`
	EndDate   time.Time `json:"enddate"`
}

SleepMeasuresQueryParam acts as the config parameter for sleep measures requests.

type SleepMeasuresResp

type SleepMeasuresResp struct {
	Status      status.Status          `json:"status"`
	Body        *SleepMeasuresRespBody `json:"body"`
	RawResponse []byte
	Path        string
	Error       string
}

SleepMeasuresResp represents the unmarshelled api response for sleep measures.

type SleepMeasuresRespBody

type SleepMeasuresRespBody struct {
	Series []SleepMeasure `json:"series"`
	Model  int            `json:"model"`
}

SleepMeasuresRespBody actrepresents the unmarshelled api response for sleep measures body.

type SleepSummary

type SleepSummary struct {
	ID              int64            `json:"id"`
	StartDate       int64            `json:"startdate"`
	EndDate         int64            `json:"enddate"`
	Date            string           `json:"date"`
	TimeZone        string           `json:"timezone"`
	Model           int              `json:"model"`
	Data            SleepSummaryData `json:"data"`
	Modified        int64            `json:"modified"`
	StartDateParsed *time.Time       `json:"startdateparsed"`
	EndDateParsed   *time.Time       `json:"enddateparsed"`
	DateParsed      *time.Time       `json:"dateparsed"`
}

SleepSummary is a summary of one sleep entry.

type SleepSummaryBody

type SleepSummaryBody struct {
	Series []SleepSummary `json:"series"`
	More   bool           `json:"more"`
}

SleepSummaryBody represents the unmarshelled api response for the sleep summary body.

type SleepSummaryData

type SleepSummaryData struct {
	WakeUpDuration     int  `json:"wakeupduration"`
	LightSleepDuration int  `json:"lightsleepduration"`
	DeepSleepDuration  int  `json:"deepsleepduration"`
	REMSleepDuration   *int `json:"remsleepduration"`
	WakeUpCount        int  `json:"wakeupcount"`
	DurationToSleep    int  `json:"durationtosleep"`
	DurationToWakeUp   *int `json:"durationtowakeup"`
}

SleepSummaryData contains the summary data for the sleep summary. Not all fields are required so some are pointers and can be nil.

type SleepSummaryQueryParam

type SleepSummaryQueryParam struct {
	StartDateYMD *time.Time `json:"startdateymd"`
	EndDateYMD   *time.Time `json:"enddateymd"`
	LastUpdate   *int64     `json:"lastupdate"`
	Offset       *int       `json:"offset"`
}

SleepSummaryQueryParam provides the query parameters for requests of sleep summary data. A date must be specified either with the StartDateYMD/EndDateYMD pair or setting the LastUpdate. The LastUpdate allow setting to zero for the first call so a time.Time struct is not accepted but rather the raw UNIX time.

type SleepSummaryResp

type SleepSummaryResp struct {
	Status      status.Status     `json:"status"`
	Body        *SleepSummaryBody `json:"body"`
	RawResponse []byte
	Path        string
	Error       string
}

SleepSummaryResp represents the unmarshelled api response for sleep summary.

type SystolicBloodPressure

type SystolicBloodPressure struct {
	Date     time.Time
	MmHg     float64
	Attrib   int
	Category int
}

type Temperature

type Temperature struct {
	Date     time.Time
	Celcius  float64
	Attrib   int
	Category int
}

type User

type User struct {
	*Client
	OauthToken *oauth2.Token
	HTTPClient *http.Client
}

User is a Withings Health user account that can be interacted with via the api. A user object should not be copied.

func (*User) CreateNotification

func (u *User) CreateNotification(params *CreateNotificationParam) (CreateNotificationResp, error)

CreateNotification is the same as CreateNotificationCtx but doesn't require a context to be provided.

func (*User) CreateNotificationCtx

func (u *User) CreateNotificationCtx(ctx context.Context, params *CreateNotificationParam) (CreateNotificationResp, error)

CreateNotificationCtx creates a new notification.

func (*User) GetActivityMeasures

func (u *User) GetActivityMeasures(params *ActivityMeasuresQueryParam) (ActivitiesMeasuresResp, error)

GetActivityMeasures is the same as GetActivityMeasuresCtx but doesn't require a context to be provided.

func (*User) GetActivityMeasuresCtx

func (u *User) GetActivityMeasuresCtx(ctx context.Context, params *ActivityMeasuresQueryParam) (ActivitiesMeasuresResp, error)

GetActivityMeasuresCtx retrieves the activity measurements as specified by the config provided. If the start time is missing the current time minus one day will be used. If the end time is missing the current day will be used.

func (*User) GetBodyMeasures

func (u *User) GetBodyMeasures(params *BodyMeasuresQueryParams) (BodyMeasuresResp, error)

GetBodyMeasures is the same as GetBodyMeasuresCtx but doesn't require a context to be provided.

func (*User) GetBodyMeasuresCtx

func (u *User) GetBodyMeasuresCtx(ctx context.Context, params *BodyMeasuresQueryParams) (BodyMeasuresResp, error)

GetBodyMeasuresCtx retrieves the body measurements as specified by the config provided.

func (*User) GetIntradayActivity

func (u *User) GetIntradayActivity(params *IntradayActivityQueryParam) (IntradayActivityResp, error)

GetIntradayActivity is the same as GetIntraDayActivityCtx but doesn't require a context to be provided.

func (*User) GetIntradayActivityCtx

func (u *User) GetIntradayActivityCtx(ctx context.Context, params *IntradayActivityQueryParam) (IntradayActivityResp, error)

GetIntradayActivityCtx retreieves intraday activites from the API. Special permissions provided by Withings Health are required to use this resource.

func (*User) GetNotificationInformation

func (u *User) GetNotificationInformation(params *NotificationInfoParam) (NotificationInfoResp, error)

GetNotificationInformation is the same as GetNotificationInformationCtx but doesn't require a context to be provided.

func (*User) GetNotificationInformationCtx

func (u *User) GetNotificationInformationCtx(ctx context.Context, params *NotificationInfoParam) (NotificationInfoResp, error)

GetNotificationInformationCtx lists all the notifications found for the user.

func (*User) GetSleepMeasures

func (u *User) GetSleepMeasures(params *SleepMeasuresQueryParam) (SleepMeasuresResp, error)

GetSleepMeasures is the same as GetSleepMeasuresCtx but doesn't require a context to be provided.

func (*User) GetSleepMeasuresCtx

func (u *User) GetSleepMeasuresCtx(ctx context.Context, params *SleepMeasuresQueryParam) (SleepMeasuresResp, error)

GetSleepMeasuresCtx retrieves the sleep measurements as specified by the config provided. Start and end dates are requires so if the param is not provided one is generated for the past 24 hour timeframe.

func (*User) GetSleepSummary

func (u *User) GetSleepSummary(params *SleepSummaryQueryParam) (SleepSummaryResp, error)

GetSleepSummary is the same as GetSleepSummaryCtx but doesn't require a context to be provided.

func (*User) GetSleepSummaryCtx

func (u *User) GetSleepSummaryCtx(ctx context.Context, params *SleepSummaryQueryParam) (SleepSummaryResp, error)

GetSleepSummaryCtx retrieves the sleep summary information provided. A SleepSummaryQueryParam is required as a timeframe is needed by the API. If null is provided the last 24 hours will be used.

func (*User) GetWorkouts

func (u *User) GetWorkouts(params *WorkoutsQueryParam) (WorkoutResponse, error)

GetWorkouts is the same as GetWorkoutsCTX but doesn't require a context to be provided.

func (*User) GetWorkoutsCtx

func (u *User) GetWorkoutsCtx(ctx context.Context, params *WorkoutsQueryParam) (WorkoutResponse, error)

GetWorkoutsCtx retrieves all the workouts for a given date range based on the values provided by params.

func (*User) ListNotifications

func (u *User) ListNotifications(params *ListNotificationsParam) (ListNotificationsResp, error)

ListNotifications is the same as ListNotificationsCtx but doesn't require a context to be provided.

func (*User) ListNotificationsCtx

func (u *User) ListNotificationsCtx(ctx context.Context, params *ListNotificationsParam) (ListNotificationsResp, error)

ListNotificationsCtx lists all the notifications found for the user.

func (*User) RevokeNotification

func (u *User) RevokeNotification(params *RevokeNotificationParam) (RevokeNotificationResp, error)

RevokeNotification is the same as RevokeNotificationCtx but doesn't require a context to be provided.

func (*User) RevokeNotificationCtx

func (u *User) RevokeNotificationCtx(ctx context.Context, params *RevokeNotificationParam) (RevokeNotificationResp, error)

RevokeNotificationCtx revokes a notification so it no longer sends.

func (*User) RoundTrip

func (u *User) RoundTrip(req *http.Request) (resp *http.Response, err error)

func (*User) Token

func (u *User) Token() (*oauth2.Token, error)

Token returns the user's oauth token, refreshing it if necessary. After a call to Token, the OauthToken field may have changed, and RefreshToken should persisted if so.

func (*User) TokenContext

func (u *User) TokenContext(ctx context.Context) (*oauth2.Token, error)

TokenContext is as per Token, above, but accepts a context, which will be used for API calls if necessary.

type UserId

type UserId string

func (*UserId) UnmarshalJSON

func (u *UserId) UnmarshalJSON(data []byte) error

type Weight

type Weight struct {
	Date     time.Time
	Kgs      float64
	Attrib   int
	Category int
}

type WithingsRoundTripper

type WithingsRoundTripper http.Client

WithingsRoundTripper unwraps withings responses so the oauth2 library can function happily.

func (*WithingsRoundTripper) RoundTrip

func (w *WithingsRoundTripper) RoundTrip(request *http.Request) (*http.Response, error)

type Workout

type Workout struct {
	ID              int                      `json:"id"`
	UserID          int                      `json:"userid"`
	Category        *workouttype.WorkoutType `json:"category"`
	StartDate       int64                    `json:"startdate"`
	EndDate         int64                    `json:"enddate"`
	Model           int                      `json:"model"`
	Attrib          int                      `json:"attrib"`
	Date            string                   `json:"date"`
	TimeZone        string                   `json:"timezone"`
	Modified        int                      `json:"modified"`
	Data            map[string]float64       `json:"data"`
	StartDateParsed *time.Time               `json:"startdateparsed"`
	EndDateParsed   *time.Time               `json:"enddateparsed"`
	DateParsed      *time.Time               `json:"dateparsed"`
}

Workout contains each workout entry as returned by the API. The raw dates are provided but fully parsed timeTime structs can be accessed via the same name as the field but with Parsed added. i.e. StartDate => StartDateParsed

type WorkoutRespBody

type WorkoutRespBody struct {
	Series []Workout `json:"series"`
}

WorkoutRespBody represents the unmarshelled body of the workout api resposne.

type WorkoutResponse

type WorkoutResponse struct {
	Status      status.Status    `json:"status"`
	Body        *WorkoutRespBody `json:"body"`
	RawResponse []byte
	Path        string
	Error       string
}

WorkoutResponse represents the unmarshelled api response for workouts.

type WorkoutsQueryParam

type WorkoutsQueryParam struct {
	UserID       int        `json:"userid"`
	StartDateYMD *time.Time `json:"startdateymd"`
	EndDateYMD   *time.Time `json:"enddateymd"`
}

WorkoutsQueryParam acts as the config parameter for workout retrieval requests.

Directories

Path Synopsis
cmd
clionly
This provides a simple cli based tool to test the interface.
This provides a simple cli based tool to test the interface.
gettoken
This provides a simple cli based tool to test the interface.
This provides a simple cli based tool to test the interface.
enum

Jump to

Keyboard shortcuts

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