Fixup: Pass RestingHeartRate to SetHeartRate().
[kraftakt.git] / gfit / gfit.go
index ac4815e..ea41b95 100644 (file)
@@ -8,6 +8,7 @@ import (
        "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,15 +21,16 @@ 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{
        ClientID:     "@GOOGLE_CLIENT_ID@",
        ClientSecret: "@GOOGLE_CLIENT_SECRET@",
        Endpoint:     oauth2google.Endpoint,
-       RedirectURL:  "https://fitbit-gfit-sync.appspot.com/google/grant",
+       RedirectURL:  "https://kraftakt.octo.it/google/grant",
        Scopes: []string{
                fitness.FitnessActivityWriteScope,
                fitness.FitnessBodyWriteScope,
@@ -144,96 +146,26 @@ func (c *Client) DataSetPatch(ctx context.Context, dataSourceID string, points [
        return nil
 }
 
-func (c *Client) Steps(ctx context.Context, startTime, endTime time.Time) (int, time.Time, error) {
-       dataSourceID := DataStreamID(&fitness.DataSource{
-               Type: "raw",
-               DataType: &fitness.DataType{
-                       Name: dataTypeNameSteps,
-               },
-       })
-       datasetID := fmt.Sprintf("%d-%d", startTime.UnixNano(), endTime.UnixNano())
-
-       res, err := c.Service.Users.DataSources.Datasets.Get(userID, dataSourceID, datasetID).Context(ctx).Do()
-       if err != nil {
-               log.Errorf(ctx, "c.Service.Users.DataSources.Datasets.Get(%q, %q) = %v",
-                       dataSourceID, datasetID, err)
-               return 0, time.Time{}, err
-       }
-
-       if len(res.Point) == 0 {
-               return 0, startTime, nil
-       }
-
-       steps := 0
-       maxEndTime := startTime
-       for _, p := range res.Point {
-               pointEndTime := time.Unix(0, p.EndTimeNanos).In(startTime.Location())
-               value := p.Value[0].IntVal
-
-               steps += int(value)
-               if maxEndTime.Before(pointEndTime) {
-                       maxEndTime = pointEndTime
-               }
-       }
-
-       log.Debugf(ctx, "Google Fit has data points until %v: %d steps", maxEndTime, steps)
-       return steps, maxEndTime, nil
-}
-
 func (c *Client) SetSteps(ctx context.Context, totalSteps int, startOfDay time.Time) error {
-       if totalSteps == 0 {
-               return nil
-       }
-
-       dataSourceID, err := c.DataSourceCreate(ctx, &fitness.DataSource{
-               Application:    Application(ctx),
-               DataStreamName: "", // "daily summary"?
-               DataType: &fitness.DataType{
-                       Field: []*fitness.DataTypeField{
-                               &fitness.DataTypeField{
-                                       Format: "integer",
-                                       Name:   "steps",
+       return c.updateCumulative(ctx,
+               &fitness.DataSource{
+                       Application: Application(ctx),
+                       DataType: &fitness.DataType{
+                               Field: []*fitness.DataTypeField{
+                                       &fitness.DataTypeField{
+                                               Name:   "steps",
+                                               Format: "integer",
+                                       },
                                },
+                               Name: dataTypeNameSteps,
                        },
-                       Name: dataTypeNameSteps,
+                       Name: "Step Count",
+                       Type: "raw",
                },
-               Name: "Step Count",
-               Type: "raw",
-               // Type: "derived",
-       })
-       if err != nil {
-               return err
-       }
-
-       endOfDay := startOfDay.Add(24 * time.Hour).Add(-1 * time.Nanosecond)
-       prevSteps, startTime, err := c.Steps(ctx, startOfDay, endOfDay)
-       if totalSteps == prevSteps {
-               return nil
-       }
-       diffSteps := totalSteps - prevSteps
-       if diffSteps < 0 {
-               log.Warningf(ctx, "c.Steps returned %d steps, but current count is %d", prevSteps, totalSteps)
-               diffSteps = totalSteps
-       }
-       endTime := endOfDay
-       if now := time.Now().In(startOfDay.Location()); now.Before(endOfDay) {
-               endTime = now
-       }
-       log.Debugf(ctx, "new data point: %v-%v %d steps", startTime, endTime, diffSteps)
-
-       return c.DataSetPatch(ctx, dataSourceID, []*fitness.DataPoint{
-               &fitness.DataPoint{
-                       ComputationTimeMillis: time.Now().UnixNano() / 1000000,
-                       DataTypeName:          dataTypeNameSteps,
-                       StartTimeNanos:        startTime.UnixNano(),
-                       EndTimeNanos:          endTime.UnixNano(),
-                       Value: []*fitness.Value{
-                               &fitness.Value{
-                                       IntVal: int64(diffSteps),
-                               },
-                       },
+               &fitness.Value{
+                       IntVal: int64(totalSteps),
                },
-       })
+               startOfDay)
 }
 
 func (c *Client) SetCalories(ctx context.Context, totalCalories float64, startOfDay time.Time) error {
@@ -306,7 +238,7 @@ func (c *Client) updateCumulative(ctx context.Context, dataSource *fitness.DataS
        if now := time.Now().In(startOfDay.Location()); now.Before(endOfDay) {
                endTime = now
        }
-       log.Debugf(ctx, "new cumulative data point: [%v--%v] %+v", startTime, endTime, diffValue)
+       log.Debugf(ctx, "adding cumulative data point: %v-%v %+v", startTime, endTime, diffValue)
 
        return c.DataSetPatch(ctx, dataSource.DataStreamId, []*fitness.DataPoint{
                &fitness.DataPoint{
@@ -349,6 +281,168 @@ func (c *Client) readCumulative(ctx context.Context, dataSource *fitness.DataSou
                }
        }
 
-       log.Debugf(ctx, "Google Fit has data points for %s until %v: %+v", dataSource.DataStreamId, maxEndTime, sum)
+       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, restingHeartRate int, 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
+               }
+
+               average := float64(d.Min+d.Max) / 2.0
+               if d.Min <= restingHeartRate && restingHeartRate <= d.Max {
+                       average = float64(restingHeartRate)
+               }
+
+               dataPoints = append(dataPoints, &fitness.DataPoint{
+                       DataTypeName:   dataSource.DataType.Name,
+                       StartTimeNanos: startTime.UnixNano(),
+                       EndTimeNanos:   endTime.UnixNano(),
+                       Value: []*fitness.Value{
+                               &fitness.Value{
+                                       FpVal: average,
+                               },
+                               &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)
+}