通过C#Google Fit api插入重量数据时出错

问题描述 投票:1回答:1

我在做什么错?将数据插入GoogleFit时出现错误(最后一行)。我知道C#API不包含详细的错误信息,但我不知道如何通过Google控制台网站发送它。

Google.GoogleApiException HResult = 0x80131500Message = Google.Apis.Requests.RequestError错误的请求[400]错误[消息[错误请求]位置[-]原因[invalidArgument]域[全局]]

using Google.Apis.Auth.OAuth2;
using Google.Apis.Fitness.v1;
using Google.Apis.Fitness.v1.Data;
using Google.Apis.Services;
using Google.Apis.Util.Store;
using System;
using System.Collections.Generic;
using System.Threading;

namespace GoogleFitImport
{
    class Program
    {
        static void Main(string[] args)
        {
            GoogleFitImport.InsertToGoogleFit();
        }
    }

    public class GoogleFitImport
    {
        private static readonly DateTime zero = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

        public static long ToJavaMiliseconds(DateTime dt)
        {
            return (long)(dt - zero).TotalMilliseconds;
        }

        public static long ToJavaNanoseconds(DateTime dt)
        {
            return (long)(dt - zero).TotalMilliseconds * 10 ^ 6;
        }

        public static DateTime FromJavaNanoseconds(long? nanoseconds)
        {
            if (nanoseconds == null)
                nanoseconds = 0;
            return FromJavaMiliseconds((nanoseconds.Value / (10 ^ 6)));
        }

        public static DateTime FromJavaMiliseconds(long mili)
        {
            return zero.AddMilliseconds((double)mili);
        }

        public static void InsertToGoogleFit()
        {
            string UserId = "me";
            List<KeyValuePair<DateTime, float>> measures = new List<KeyValuePair<DateTime, float>>();
            measures.Add(new KeyValuePair<DateTime, float>(new DateTime(2000, 01, 01, 12, 0, 0, DateTimeKind.Utc), 10.1f));
            measures.Add(new KeyValuePair<DateTime, float>(new DateTime(2000, 01, 02, 12, 0, 0, DateTimeKind.Utc), 10.2f));
            measures.Add(new KeyValuePair<DateTime, float>(new DateTime(2000, 01, 03, 12, 0, 0, DateTimeKind.Utc), 10.3f));

            //  https://www.googleapis.com/auth/fitness.body.write
            var clientId = "000000000000-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com"; // From https://console.developers.google.com
            var clientSecret = "XXXXXXXXXXXXXXXXXXXXXXXX"; // From https://console.developers.google.com

            //Scopes for use with the Google Drive API
            string[] scopes = new string[]
            {
                FitnessService.Scope.FitnessBodyWrite,
                FitnessService.Scope.FitnessBodyRead,
            };

            // here is where we Request the user to give us access, or use the Refresh Token that was previously stored in %AppData%
            var credential = GoogleWebAuthorizationBroker.AuthorizeAsync
            (
                new ClientSecrets
                {
                    ClientId = clientId,
                    ClientSecret = clientSecret
                },
                scopes,
                Environment.UserName,
                CancellationToken.None,
                new FileDataStore("Google.Fitness.Auth", false)
            ).Result;


            FitnessService fitnessService = new FitnessService(new BaseClientService.Initializer()
            {
                HttpClientInitializer = credential,
                ApplicationName = "FromLibraCsvToGoogleFit" //Assembly.GetExecutingAssembly().GetName().Name,
            });


            DataSource dataSource = new DataSource()
            {
                Type = "raw", //""derived",
                Application = new Google.Apis.Fitness.v1.Data.Application()
                {
                    Name = "maweightimport"
                },
                DataType = new DataType()
                {
                    Name = "com.google.weight",
                    Field = new List<DataTypeField>()
                    {
                        new DataTypeField() {Name = "weight", Format = "floatPoint"}
                    }
                },
                Device = new Device()
                {
                    Type = "scale",
                    Manufacturer = "unknown",
                    Model = "unknown",
                    Uid = "maweightimport",
                    Version = "1.0"
                }
            };

            //string dataSourceId = "derived:com.google.weight:{clientId}:unknown:unknown:maweightimport"
            string dataSourceId =
                $"{dataSource.Type}:{dataSource.DataType.Name}:{clientId.Split('-')[0]}:{dataSource.Device.Manufacturer}:{dataSource.Device.Model}:{dataSource.Device.Uid}";

            try
            {
                DataSource googleDataSource = fitnessService.Users.DataSources.Get(UserId, dataSourceId).Execute();
            }
            catch (Exception ex) //create if not exists
            {
                Console.WriteLine(ex);
                DataSource googleDataSource = fitnessService.Users.DataSources.Create(dataSource, UserId).Execute();
            }

            Google.Apis.Fitness.v1.Data.Dataset weightsDataSource = new Google.Apis.Fitness.v1.Data.Dataset()
            {
                DataSourceId = dataSourceId,
                Point = new List<DataPoint>()
            };

            DateTime minDateTime = DateTime.MaxValue;
            DateTime maxDateTime = DateTime.MinValue;
            foreach (var weight in measures)
            {
                long ts = ToJavaNanoseconds(weight.Key);
                weightsDataSource.Point.Add
                (
                    new DataPoint()
                    {
                        DataTypeName = "com.google.weight",
                        StartTimeNanos = ts,
                        EndTimeNanos = ts,
                        Value = new List<Value>()
                        {
                            new Value()
                            {
                                FpVal = weight.Value
                            }
                        }
                    }
                );

                if (minDateTime > weight.Key)
                    minDateTime = weight.Key;
                if (maxDateTime < weight.Key)
                    maxDateTime = weight.Key;
            }

            weightsDataSource.MinStartTimeNs = ToJavaNanoseconds(minDateTime);
            weightsDataSource.MaxEndTimeNs = ToJavaNanoseconds(maxDateTime);

            string dataSetId = "2000.01.01-2000.01.03";
            var save = fitnessService.Users.DataSources.Datasets.Patch(weightsDataSource, UserId, dataSourceId, dataSetId).Execute(); //ERROR HERE !
            //var read = fitnessService.Users.DataSources.Datasets.Get(UserId, dataSourceId, dataSetId).Execute();
        }
    }
}
c# google-api console-application google-fit
1个回答
0
投票
string dataSetId = "2000.01.01-2000.01.03";

必须在Nanos中。

© www.soinside.com 2019 - 2024. All rights reserved.