From 2eac6c527c6997568372a3f3e3d7c09d86aec78e Mon Sep 17 00:00:00 2001 From: Florian Forster Date: Tue, 16 Jan 2018 17:14:58 +0100 Subject: [PATCH] Implement mapping of heart rate zones. --- fitbit/fitbit.go | 1 + gfit/gfit.go | 164 ++++++++++++++++++++++++++++++++++++++++++++++++++++++- gfitsync.go | 4 ++ 3 files changed, 167 insertions(+), 2 deletions(-) diff --git a/fitbit/fitbit.go b/fitbit/fitbit.go index f534906..f871604 100644 --- a/fitbit/fitbit.go +++ b/fitbit/fitbit.go @@ -109,6 +109,7 @@ type ActivitySummary struct { Elevation float64 `json:"elevation"` Floors int `json:"floors"` HeartRateZones []HeartRateZone `json:"heartRateZones"` + CustomHeartRateZones []HeartRateZone `json:"customHeartRateZones"` MarginalCalories int `json:"marginalCalories"` RestingHeartRate int `json:"restingHeartRate"` Steps int `json:"steps"` diff --git a/gfit/gfit.go b/gfit/gfit.go index d447bc0..fcd88f1 100644 --- a/gfit/gfit.go +++ b/gfit/gfit.go @@ -3,11 +3,13 @@ package gfit import ( "context" "fmt" + "math" "net/http" "strings" "time" "github.com/octo/gfitsync/app" + "github.com/octo/gfitsync/fitbit" "golang.org/x/oauth2" oauth2google "golang.org/x/oauth2/google" fitness "google.golang.org/api/fitness/v1" @@ -20,8 +22,9 @@ const ( csrfToken = "@CSRFTOKEN@" userID = "me" - dataTypeNameCalories = "com.google.calories.expended" - dataTypeNameSteps = "com.google.step_count.delta" + dataTypeNameCalories = "com.google.calories.expended" + dataTypeNameSteps = "com.google.step_count.delta" + dataTypeNameHeartrate = "com.google.heart_rate.summary" ) var oauthConfig = &oauth2.Config{ @@ -282,3 +285,160 @@ func (c *Client) readCumulative(ctx context.Context, dataSource *fitness.DataSou log.Debugf(ctx, "read cumulative data %s until %v: %+v", dataSource.DataStreamId, maxEndTime, sum) return &sum, maxEndTime, nil } + +type heartRateDuration struct { + Min int + Max int + Duration time.Duration +} + +type heartRateDurations []*heartRateDuration + +func (res heartRateDurations) find(min, max int) (*heartRateDuration, bool) { + for _, d := range res { + if d.Min != min || d.Max != max { + continue + } + return d, true + } + + return nil, false +} + +func (c *Client) heartRate(ctx context.Context, dataSource *fitness.DataSource, startTime, endTime time.Time) (heartRateDurations, time.Time, error) { + datasetID := fmt.Sprintf("%d-%d", startTime.UnixNano(), endTime.UnixNano()) + + res, err := c.Service.Users.DataSources.Datasets.Get(userID, dataSource.DataStreamId, datasetID).Context(ctx).Do() + if err != nil { + log.Errorf(ctx, "c.Service.Users.DataSources.Datasets.Get(%q, %q) = %v", dataSource.DataStreamId, datasetID, err) + return nil, time.Time{}, err + } + + if len(res.Point) == 0 { + return nil, startTime, nil + } + + var results heartRateDurations + maxEndTime := startTime + for _, p := range res.Point { + max := int(p.Value[1].FpVal) + min := int(p.Value[2].FpVal) + duration := time.Unix(0, p.EndTimeNanos).Sub(time.Unix(0, p.StartTimeNanos)) + + if d, ok := results.find(min, max); ok { + d.Duration += duration + } else { + results = append(results, &heartRateDuration{ + Min: min, + Max: max, + Duration: duration, + }) + } + + pointEndTime := time.Unix(0, p.EndTimeNanos).In(startTime.Location()) + if maxEndTime.Before(pointEndTime) { + maxEndTime = pointEndTime + } + } + + return results, maxEndTime, nil +} + +func (c *Client) SetHeartRate(ctx context.Context, totalDurations []fitbit.HeartRateZone, startOfDay time.Time) error { + dataSource := &fitness.DataSource{ + Application: Application(ctx), + DataType: &fitness.DataType{ + Field: []*fitness.DataTypeField{ + &fitness.DataTypeField{ + Name: "average", + Format: "floatPoint", + }, + &fitness.DataTypeField{ + Name: "max", + Format: "floatPoint", + }, + &fitness.DataTypeField{ + Name: "min", + Format: "floatPoint", + }, + }, + Name: dataTypeNameHeartrate, + }, + Name: "Heart rate summary", + Type: "raw", + } + + dataSourceID, err := c.DataSourceCreate(ctx, dataSource) + if err != nil { + return err + } + dataSource.DataStreamId = dataSourceID + + endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond) + prevDurations, startTime, err := c.heartRate(ctx, dataSource, startOfDay, endOfDay) + + // calculate the difference between the durations mentioned in + // totalDurations and prevDurations and store it in diffDurations. + var diffDurations heartRateDurations + for _, d := range totalDurations { + total := time.Duration(d.Minutes) * time.Minute + + var prev time.Duration + if res, ok := prevDurations.find(d.Min, d.Max); ok { + prev = res.Duration + } + + diff := total - prev + if diff < 0 { + diff = total + } + + if res, ok := diffDurations.find(d.Min, d.Max); ok { + res.Duration += diff + } else { + diffDurations = append(diffDurations, &heartRateDuration{ + Min: d.Min, + Max: d.Max, + Duration: diff, + }) + } + } + + // create a fitness.DataPoint for each non-zero duration difference. + var dataPoints []*fitness.DataPoint + for _, d := range diffDurations { + if d.Duration < time.Nanosecond { + continue + } + + endTime := startTime.Add(d.Duration) + if endTime.After(endOfDay) { + log.Warningf(ctx, "heart rate durations exceed one day (current end time: %v)", endTime) + break + } + + dataPoints = append(dataPoints, &fitness.DataPoint{ + DataTypeName: dataSource.DataType.Name, + StartTimeNanos: startTime.UnixNano(), + EndTimeNanos: endTime.UnixNano(), + Value: []*fitness.Value{ + &fitness.Value{ + FpVal: math.NaN(), + }, + &fitness.Value{ + FpVal: float64(d.Max), + }, + &fitness.Value{ + FpVal: float64(d.Min), + }, + }, + }) + + startTime = endTime + } + + if len(dataPoints) == 0 { + return nil + } + return c.DataSetPatch(ctx, dataSource.DataStreamId, dataPoints) +} diff --git a/gfitsync.go b/gfitsync.go index f12e7f4..29f98ae 100644 --- a/gfitsync.go +++ b/gfitsync.go @@ -259,5 +259,9 @@ func handleNotification(ctx context.Context, s *fitbit.Subscription) error { return fmt.Errorf("gfitClient.SetCalories(%d) = %v", summary.Summary.CaloriesOut, err) } + if err := gfitClient.SetHeartRate(ctx, summary.Summary.HeartRateZones, tm); err != nil { + return fmt.Errorf("gfitClient.SetHeartRate() = %v", err) + } + return nil } -- 2.11.0