private async Task <List <WalkingDataPointModel> > QuerySpeedDataBetween(DateTime bucketStart, DateTime bucketStop) { var speedRequest = new DataReadRequest.Builder() .Aggregate(DataType.TypeSpeed, DataType.AggregateSpeedSummary) .BucketByTime(1, TimeUnit.Minutes) .SetTimeRange(bucketStart.ToUnixTime(), bucketStop.ToUnixTime(), TimeUnit.Milliseconds) .Build(); var speedResponse = await fitnessHistoryClient.ReadDataAsync(speedRequest); if (speedResponse.Status.IsSuccess) { var dataSets = speedResponse.Buckets.SelectMany(b => b.DataSets).ToList(); var dataPoints = dataSets.SelectMany(ds => ds.DataPoints).ToList(); return(speedResponse.Buckets .SelectMany(b => b.DataSets) .SelectMany(ds => ds.DataPoints) .Select(dp => { //convert the times var start = dp.GetStartTime(TimeUnit.Milliseconds).DateTimeFromUnixTime(); var end = dp.GetEndTime(TimeUnit.Milliseconds).DateTimeFromUnixTime(); if (start == end) { end = end.AddMinutes(1); } var average = dp.GetValue(Field.FieldAverage).AsFloat(); if (average > 0.1f && average < 12) { #if DUMP_DATA WalkingDataPointModel res = new WalkingDataPointModel(start, end, average); using (System.IO.FileStream fs = new System.IO.FileStream(dumpFilePath, System.IO.FileMode.Append)) { dumpSerializer.Serialize(fs, res); } return res; #else return new WalkingDataPointModel(start, end, average); #endif } return null; }) .Where(dp => dp != null) .ToList()); } #if DEBUG Debug.WriteLine($"Failed to poll speed data: {speedResponse.Status.StatusMessage}"); #else Crashes.TrackError(new Exception($"Failed to poll speed data: {speedResponse.Status.StatusMessage}"), new Dictionary <string, string> { { "StatusMessage", speedResponse.Status.StatusMessage } }); #endif return(null); }
static DataReadRequest queryStepsData() { DateTime endTime = DateTime.Now; //DateTime startTime = endTime.Subtract(TimeSpan.FromDays(7)); DateTime startTime = DateTime.Today; long endTimeElapsed = GetMsSinceEpochAsLong(endTime); long startTimeElapsed = GetMsSinceEpochAsLong(startTime); Log.Info("googleFitFetch", "Range Start: " + startTime.ToString(DATE_FORMAT)); Log.Info("googleFitFetch", "Range End: " + endTime.ToString(DATE_FORMAT)); DataSource source = new DataSource.Builder() .SetAppPackageName("com.google.android.gms") .SetDataType(Android.Gms.Fitness.Data.DataType.TypeStepCountDelta) .SetType(DataSource.TypeDerived) .SetStreamName("estimated_steps") .Build(); var readRequest = new DataReadRequest.Builder() .Aggregate(source, Android.Gms.Fitness.Data.DataType.AggregateStepCountDelta) .BucketByTime(1, TimeUnit.Days) .SetTimeRange(startTimeElapsed, endTimeElapsed, TimeUnit.Milliseconds) .Build(); return(readRequest); }
private async Task testSteps3() { DataSource dataSource = new DataSource.Builder() .SetAppPackageName("com.google.android.gms") .SetDataType(DataType.TypeStepCountDelta) //.SetDataType(DataType.AggregateStepCountDelta) .SetType(DataSource.TypeDerived) .SetStreamName("estimated_steps") .Build(); var cal = Calendar.Instance; var now = new Date(); cal.Time = now; var endTime = cal.TimeInMillis; cal.Add(CalendarField.WeekOfYear, -1); var startTime = cal.TimeInMillis; DataReadRequest readRequest = new DataReadRequest.Builder() //.Aggregate(DataType.TypeStepCountDelta, DataType.AggregateStepCountDelta) //.Aggregate(dataSource, DataType.AggregateStepCountDelta) .Aggregate(dataSource, DataType.TypeStepCountDelta) .BucketByTime(1, TimeUnit.Days) .SetTimeRange(startTime, endTime, TimeUnit.Milliseconds) .Build(); var dataReadResult = await FitnessClass.HistoryApi.ReadDataAsync(client, readRequest); if (dataReadResult.Status.IsSuccess) { foreach (var item in dataReadResult.DataSets) { var a = item; } foreach (Bucket item in dataReadResult.Buckets) { var t = item.DataSets; var a = item; foreach (var ds in item.DataSets) { foreach (var dp in ds.DataPoints) { foreach (var field in dp.DataType.Fields) { var b = dp.GetValue(field); } } } } } }
public async void ActiveTimeByPeriod(DateTime start, DateTime end, Action <IEnumerable <TimeSpan> > act) { start = TimeZoneInfo.ConvertTimeToUtc(start); end = TimeZoneInfo.ConvertTimeToUtc(end); using (DataReadRequest time = new DataReadRequest.Builder() .Aggregate(DataType.TypeActivitySegment, DataType.AggregateActivitySummary) .BucketByTime(1, TimeUnit.Days) .SetTimeRange(TimeUtility.DatetimeInMillis(start), TimeUtility.DatetimeInMillis(end), TimeUnit.Milliseconds) .Build()) using (DataReadResult caloriesResult = (DataReadResult)await ReadData(time)) act?.Invoke(GetIntFromResult(caloriesResult, new string[] { "duration" }).Select(x => TimeSpan.FromMinutes(x))); }
public async void CaloriesByPeriod(DateTime start, DateTime end, Action <IEnumerable <double> > act) { start = TimeZoneInfo.ConvertTimeToUtc(start); end = TimeZoneInfo.ConvertTimeToUtc(end); using (DataReadRequest caloriesRequest = new DataReadRequest.Builder() .Aggregate(DataType.TypeCaloriesExpended, DataType.AggregateCaloriesExpended) .BucketByTime(1, TimeUnit.Days) .SetTimeRange(TimeUtility.DatetimeInMillis(start), TimeUtility.DatetimeInMillis(end), TimeUnit.Milliseconds) .Build()) using (DataReadResult caloriesResult = (DataReadResult)await ReadData(caloriesRequest)) act?.Invoke(GetFloatFromResult(caloriesResult).Select(x => Math.Round(x))); }
async Task <List <StepCountEntry> > UpdateStepEntries() { //https://github.com/xamarin/monodroid-samples/blob/master/google-services/Fitness/BasicHistoryApi/BasicHistoryApi/MainActivity.cs DateTime endTime = DateTime.Now; DateTime startTime = endTime.Subtract(TimeSpan.FromDays(7)); long endTimeElapsed = GetMsSinceEpochAsLong(endTime); long startTimeElapsed = GetMsSinceEpochAsLong(startTime); var readRequest = new DataReadRequest.Builder() .Aggregate(Android.Gms.Fitness.Data.DataType.TypeStepCountDelta, Android.Gms.Fitness.Data.DataType.AggregateStepCountDelta) .SetTimeRange(startTimeElapsed, endTimeElapsed, TimeUnit.Milliseconds) .BucketByTime(1, TimeUnit.Days) .Build(); var readResult = await FitnessClass.HistoryApi.ReadDataAsync(mClient, readRequest); if (!readResult.Status.IsSuccess) { if (readResult.Status.HasResolution) { readResult.Status.StartResolutionForResult(_activity, REQUEST_GET_REQUEST_PERMISSION); return(null); } } var stepCountEntryList = new List <StepCountEntry>(); foreach (var bucket in readResult.Buckets) { var dataSet = bucket.DataSets.LastOrDefault(); if (dataSet != null) { var value = GetLastValueInDataSet(dataSet); if (value != null) { stepCountEntryList.Add(new StepCountEntry(Convert.ToDouble(value.AsInt()))); } } } //We should have a bucket per day, parse it all out. return(stepCountEntryList); }
DataReadRequest QueryFitnessData() { var epoch = new DateTime(1970, 1, 1); var now = DateTime.UtcNow; var endTime = (now - epoch).TotalMilliseconds; var startTime = (now.Subtract(TimeSpan.FromDays(7)) - epoch).TotalMilliseconds; Log.Info(TAG, "Range Start: " + startTime.ToString(DATE_FORMAT)); Log.Info(TAG, "Range End: " + endTime.ToString(DATE_FORMAT)); var readRequest = new DataReadRequest.Builder() .Aggregate(DataType.TypeStepCountDelta, DataType.AggregateStepCountDelta) .BucketByTime(1, TimeUnit.Days) .SetTimeRange((long)startTime, (long)endTime, TimeUnit.Milliseconds) .Build(); return(readRequest); }
DataReadRequest QueryFitnessData() { // Setting a start and end date using a range of 1 week before this moment. DateTime endTime = DateTime.Now; DateTime startTime = endTime.Subtract(TimeSpan.FromDays(7)); long endTimeElapsed = GetMsSinceEpochAsLong(endTime); long startTimeElapsed = GetMsSinceEpochAsLong(startTime); Log.Info(TAG, "Range Start: " + startTime.ToString(DATE_FORMAT)); Log.Info(TAG, "Range End: " + endTime.ToString(DATE_FORMAT)); var readRequest = new DataReadRequest.Builder() .Aggregate(DataType.TypeStepCountDelta, DataType.AggregateStepCountDelta) .BucketByTime(1, TimeUnit.Days) .SetTimeRange(startTimeElapsed, endTimeElapsed, TimeUnit.Milliseconds) .Build(); return(readRequest); }
// utility function that gets the basal metabolic rate averaged over a week private async Task <double> GetBasalAvg(DateTime endDate) { float basalAvg = 0; long startDate = endDate.AddDays(-7).ToJavaTimeStamp(); var readRequest = new DataReadRequest.Builder() .Aggregate(DataType.TypeBasalMetabolicRate, DataType.AggregateBasalMetabolicRateSummary) .BucketByTime(1, TimeUnit.Days) .SetTimeRange(startDate, endDate.ToJavaTimeStamp(), TimeUnit.Milliseconds).Build(); var response = await FitnessClass.GetHistoryClient(_currentActivity, GoogleSignIn.GetLastSignedInAccount(_currentActivity)) .ReadDataAsync(readRequest); if (response.Status.IsSuccess) { var avgsN = 0; foreach (var bucket in response.Buckets) { // in the com.google.bmr.summary data type, each data point represents // the average, maximum and minimum basal metabolic rate, in kcal per day, over the time interval of the data point. var dataSet = bucket.GetDataSet(DataType.AggregateBasalMetabolicRateSummary); foreach (var dataPoint in dataSet.DataPoints) { var avg = dataPoint.GetValue(Field.FieldAverage).AsFloat(); if (avg > 0) { basalAvg += avg; avgsN++; } } } // do the average of the averages if (avgsN != 0) { basalAvg /= avgsN; // this a daily average } return(basalAvg); } throw new Exception(response.Status.StatusMessage); }
async Task UpdateHeight() { //http://stackoverflow.com/questions/28482176/read-the-height-in-googlefit-in-android DateTime endTime = DateTime.Now; //TimeSpan has to be huge, otherwise we may never get the user's height. //May also have to query back for YEARS or multiple query in loop until you get an answer. //Don't like the Google Fit API... DateTime startTime = endTime.Subtract(TimeSpan.FromDays(1024)); long endTimeElapsed = GetMsSinceEpochAsLong(endTime); long startTimeElapsed = GetMsSinceEpochAsLong(startTime); var readRequest = new DataReadRequest.Builder() .Read(Android.Gms.Fitness.Data.DataType.TypeHeight) .SetTimeRange(startTimeElapsed, endTimeElapsed, TimeUnit.Milliseconds) .SetLimit(1) .Build(); var readResult = await FitnessClass.HistoryApi.ReadDataAsync(mClient, readRequest); if (!readResult.Status.IsSuccess) { if (readResult.Status.HasResolution) { readResult.Status.StartResolutionForResult(_activity, REQUEST_GET_REQUEST_PERMISSION); return; } } var value = GetLastValueInDataSet(readResult.DataSets.LastOrDefault()); if (value != null) { HealthStateMutator.MutateHeight( StateDispatcher <HealthState> .State, () => value.AsFloat()); } }
static DataReadRequest queryDistance() { DateTime endTime = DateTime.Now; //DateTime startTime = endTime.Subtract(TimeSpan.FromDays(7)); DateTime startTime = DateTime.Today; long endTimeElapsed = GetMsSinceEpochAsLong(endTime); long startTimeElapsed = GetMsSinceEpochAsLong(startTime); Log.Info("googleFitFetch", "Range Start: " + startTime.ToString(DATE_FORMAT)); Log.Info("googleFitFetch", "Range End: " + endTime.ToString(DATE_FORMAT)); var readRequest = new DataReadRequest.Builder() .Aggregate(Android.Gms.Fitness.Data.DataType.TypeDistanceDelta, Android.Gms.Fitness.Data.DataType.AggregateDistanceDelta) .BucketByTime(1, TimeUnit.Days) .SetTimeRange(startTimeElapsed, endTimeElapsed, TimeUnit.Milliseconds) .Build(); return(readRequest); }
async Task UpdateFood() { DateTime endTime = DateTime.Now; DateTime startTime = endTime.Subtract(TimeSpan.FromDays(7)); long endTimeElapsed = GetMsSinceEpochAsLong(endTime); long startTimeElapsed = GetMsSinceEpochAsLong(startTime); var readRequest = new DataReadRequest.Builder() .Read(Android.Gms.Fitness.Data.DataType.TypeNutrition) .SetTimeRange(startTimeElapsed, endTimeElapsed, TimeUnit.Milliseconds) .SetLimit(100) .Build(); var readResult = await FitnessClass.HistoryApi.ReadDataAsync(mClient, readRequest); //The result may need to popup additional user security dialogs for the user to grant access to the specific data points. if (!readResult.Status.IsSuccess) { if (readResult.Status.HasResolution) { readResult.Status.StartResolutionForResult(_activity, REQUEST_GET_REQUEST_PERMISSION); return; } } foreach (var dataSet in readResult.DataSets) { foreach (var dataPoint in dataSet.DataPoints) { //See if dataPoint has nutrient info in it. var foodNameValue = dataPoint.GetValue(Field.FieldFoodItem); var foodName = foodNameValue.AsString(); var nutrientsValue = dataPoint.GetValue(Field.FieldNutrients); //var calories = nutrientsValue.GetKeyValue (Field.FieldCalories); var i = 0; } } }
DataReadRequest QueryFitnessData () { // Setting a start and end date using a range of 1 week before this moment. DateTime endTime = DateTime.Now; DateTime startTime = endTime.Subtract (TimeSpan.FromDays (7)); long endTimeElapsed = GetMsSinceEpochAsLong (endTime); long startTimeElapsed = GetMsSinceEpochAsLong (startTime); Log.Info (TAG, "Range Start: " + startTime.ToString (DATE_FORMAT)); Log.Info (TAG, "Range End: " + endTime.ToString (DATE_FORMAT)); var readRequest = new DataReadRequest.Builder () .Aggregate (DataType.TypeStepCountDelta, DataType.AggregateStepCountDelta) .BucketByTime (1, TimeUnit.Days) .SetTimeRange (startTimeElapsed, endTimeElapsed, TimeUnit.Milliseconds) .Build (); return readRequest; }
protected override async Task <IEnumerable <T> > Query <T>(HealthDataType healthDataType, AggregateTime aggregateTime, DateTime startDate, DateTime endDate) { var authorized = _healthService.HasOAuthPermission(_healthService.FitnessReadOptions(new HealthDataType[] { healthDataType })); if (!authorized) { throw new UnauthorizedAccessException($"Not enough permissions to request {healthDataType}"); } var fitData = healthDataType.ToGoogleFit(); long startTime = startDate.ToJavaTimeStamp(); long endTime = endDate.ToJavaTimeStamp(); var readBuilder = new DataReadRequest.Builder() .SetTimeRange(startTime, endTime, TimeUnit.Milliseconds) .EnableServerQueries(); if (aggregateTime != AggregateTime.None) { readBuilder.Aggregate(fitData.TypeIdentifier, fitData.AggregateType); switch (aggregateTime) { case AggregateTime.Year: readBuilder.BucketByTime(365, TimeUnit.Days); break; case AggregateTime.Month: readBuilder.BucketByTime(31, TimeUnit.Days); break; case AggregateTime.Week: readBuilder.BucketByTime(7, TimeUnit.Days); break; case AggregateTime.Day: readBuilder.BucketByTime(1, TimeUnit.Days); break; case AggregateTime.Hour: readBuilder.BucketByTime(1, TimeUnit.Hours); break; } } else { readBuilder.Read(fitData.TypeIdentifier); } var readRequest = readBuilder.Build(); var response = await FitnessClass.GetHistoryClient(_currentActivity, GoogleSignIn.GetLastSignedInAccount(_currentActivity)) .ReadDataAsync(readRequest).ConfigureAwait(false); double valueToSubstract = 0; if (healthDataType == HealthDataType.CaloriesActive) { valueToSubstract = await GetBasalAvg(endDate); } if (response == null) { return(new List <T>()); } if (response.Buckets.Any()) { var output = new List <T>(); foreach (var bucket in response.Buckets) { var dataSet = bucket.GetDataSet(fitData.AggregateType); output.AddRange((IEnumerable <T>)dataSet.DataPoints.Select(result => CreateAggregatedData(result, fitData, valueToSubstract))); if (!dataSet.DataPoints.Any() && healthDataType == HealthDataType.Droid_BasalMetabolicRate) { output.Add( new AggregatedHealthData() { StartDate = bucket.GetStartTime(TimeUnit.Milliseconds).ToDateTime(), EndDate = bucket.GetEndTime(TimeUnit.Milliseconds).ToDateTime(), Sum = valueToSubstract } as T); } } return(output); } return((IEnumerable <T>)response.GetDataSet(fitData.TypeIdentifier)?.DataPoints? .Select(dataPoint => new HealthData { StartDate = dataPoint.GetStartTime(TimeUnit.Milliseconds).ToDateTime(), EndDate = dataPoint.GetEndTime(TimeUnit.Milliseconds).ToDateTime(), Value = ReadValue(dataPoint, fitData.Unit, valueToSubstract) ?? 0, UserEntered = dataPoint.OriginalDataSource?.StreamName == "user_input" }).ToList()); }
private async Task <List <WalkingDataPointModel> > QueryActivityDataBetween(DateTime bucketStart, DateTime bucketEnd) { var dailyActivityRequest = new DataReadRequest.Builder() .Aggregate(DataType.TypeActivitySegment, DataType.AggregateActivitySummary) .BucketByTime(1, TimeUnit.Minutes) .SetTimeRange(bucketStart.ToUnixTime(), bucketEnd.ToUnixTime(), TimeUnit.Milliseconds) .Build(); DataReadResponse activityResponse = null; var readTask = fitnessHistoryClient.ReadDataAsync(dailyActivityRequest); if (await Task.WhenAny(readTask, Task.Delay(30000)) == readTask) { // Task completed within timeout. // Consider that the task may have faulted or been canceled. // We re-await the task so that any exceptions/cancellation is rethrown. activityResponse = await readTask; } else { return(new List <WalkingDataPointModel>()); } if (activityResponse.Status.IsSuccess) { var activityDataPoints = activityResponse.Buckets .SelectMany(b => b.DataSets) .SelectMany(ds => ds.DataPoints) .Select(adp => { var start = adp.GetStartTime(TimeUnit.Milliseconds).DateTimeFromUnixTime(); var end = adp.GetEndTime(TimeUnit.Milliseconds).DateTimeFromUnixTime(); var activity = adp.GetValue(Field.FieldActivity).AsActivity(); // ON_FOOT // The user is on foot, walking or running. // RUNNING // The user is running. // RUNNING_JOGGING // The user is jogging. // RUNNING_SAND // The user is running on sand. // RUNNING_TREADMILL // The user is running on a treadmill. // WALKING // The user is walking. // WALKING_FITNESS // The user is walking at a moderate to high pace, for fitness. // WALKING_NORDIC // The user is performing Nordic walking(with poles). // WALKING_STROLLER // The user is walking while pushing a stroller. // WALKING_TREADMILL // The user is walking on a treadmill if (Regex.IsMatch(activity, "^(ON_FOOT|RUNNING|WALKING)", RegexOptions.IgnoreCase)) { return(new WalkingDataPointModel(start, end, 0)); } return(null); }) .Where(adp => adp != null) .ToList(); return(activityDataPoints); } #if DEBUG Debug.WriteLine($"Failed to poll speed data: {activityResponse.Status.StatusMessage}"); #else Crashes.TrackError(new Exception($"Failed to poll speed data: {activityResponse.Status.StatusMessage}"), new Dictionary <string, string> { { "StatusMessage", activityResponse.Status.StatusMessage } }); #endif return(null); }
private async Task testSteps2() { DataSource dataSource = new DataSource.Builder() .SetAppPackageName("com.google.android.gms") .SetDataType(DataType.TypeStepCountDelta) //.SetDataType(DataType.AggregateStepCountDelta) .SetType(DataSource.TypeDerived) .SetStreamName("estimated_steps") .Build(); var cal = Calendar.Instance; var now = new Date(); cal.Time = now; var endTime = cal.TimeInMillis; cal.Add(CalendarField.WeekOfYear, -1); var startTime = cal.TimeInMillis; DataReadRequest readRequest = new DataReadRequest.Builder() //.Aggregate(DataType.TypeStepCountDelta, DataType.AggregateStepCountDelta) .Aggregate(dataSource, DataType.AggregateStepCountDelta) .BucketByTime(1, TimeUnit.Days) .SetTimeRange(startTime, endTime, TimeUnit.Milliseconds) .Build(); var dataReadResult = await FitnessClass.HistoryApi.ReadDataAsync(client, readRequest); //foreach (var dataSet in dataReadResult.DataSets) //{ // var d = dataSet.DataType; //} //var test = dataReadResult.GetDataSet(DataType.TypeStepCountDelta); //var aggregatedSteps = dataReadResult.GetDataSet(DataType.AggregateStepCountDelta); //foreach (var dataPoint in aggregatedSteps.DataPoints) //{ // var a = dataPoint.GetValue(Field.FieldSteps); //} //foreach (var bucket in dataReadResult.Buckets) //{ // var dataSet = bucket.DataSets[0]; // var activity = bucket.Activity; // var bucketType = bucket.BucketType; //} DataSet test = dataReadResult.GetDataSet(DataType.TypeStepCountDelta); var stepData = dataReadResult.GetDataSet(DataType.AggregateStepCountDelta); foreach (var dp in test.DataPoints) { foreach (var field in dp.DataType.Fields) { var a = dp.GetValue(field); } } int totalSteps = 0; foreach (DataPoint dp in stepData.DataPoints) { foreach (Field field in dp.DataType.Fields) { int steps = dp.GetValue(field).AsInt(); totalSteps += steps; } } }