示例#1
0
        /// <summary>
        /// Returns steps for given day at given resolution
        /// </summary>
        /// <param name="day">Day to fetch data for</param>
        /// <param name="resolution">Resolution in minutes. Minimum resolution is five minutes.</param>
        /// <returns>List of steps counts for the given day at given resolution.</returns>
        public async Task <List <KeyValuePair <TimeSpan, uint> > > GetStepsCountsForDay(DateTime day, uint resolution)
        {
            List <KeyValuePair <TimeSpan, uint> > steps = new List <KeyValuePair <TimeSpan, uint> >();
            uint numIntervals = (((24 * 60) / resolution) + 1);

            if (day.Date.Equals(DateTime.Today))
            {
                numIntervals = (uint)((DateTime.Now - DateTime.Today).TotalMinutes / resolution) + 1;
            }

            uint totalSteps = 0;

            for (uint i = 0; i < numIntervals; i++)
            {
                TimeSpan ts        = TimeSpan.FromMinutes(i * resolution);
                DateTime startTime = day.Date + ts;
                if (startTime < DateTime.Now)
                {
                    // Get history from startTime to the resolution duration
                    var readings = await Pedometer.GetSystemHistoryAsync(startTime, TimeSpan.FromMinutes(resolution));

                    // Compute the deltas
                    var stepsDelta = StepCountData.FromPedometerReadings(readings);

                    // Add to the total count
                    totalSteps += stepsDelta.TotalCount;
                    steps.Add(new KeyValuePair <TimeSpan, uint>(ts, totalSteps));
                }
                else
                {
                    break;
                }
            }
            return(steps);
        }
示例#2
0
        /// <summary>
        /// Returns step count for given day
        /// </summary>
        /// <returns>Step count for given day</returns>
        public async Task <StepCountData> GetTotalStepCountAsync(DateTime day)
        {
            // Get history from 1 day
            var readings = await Pedometer.GetSystemHistoryAsync(day.Date, TimeSpan.FromDays(1));

            return(StepCountData.FromPedometerReadings(readings));
        }
示例#3
0
文件: OEMTask.cs 项目: sorryb/UWP
        /// <summary>
        /// Gets number of steps for current day
        /// </summary>
        /// <returns><c>true</c> if steps were successfully fetched, <c>false</c> otherwise</returns>
        private async Task <bool> GetStepsAsync()
        {
            // First try the pedometer
            try
            {
                var readings = await Pedometer.GetSystemHistoryAsync(DateTime.Now.Date, DateTime.Now - DateTime.Now.Date);

                _steps = StepCountData.FromPedometerReadings(readings);
                return(true);
            }
            catch (Exception)
            {
                // Continue to the fallback
            }

            // Fall back to using Lumia Sensor Core.
            IStepCounter stepCounter = null;

            try
            {
                //var qualifiers = Windows.ApplicationModel.Resources.Core.ResourceContext.GetForCurrentView().QualifierValues;

                if (DeviceTypeHelper.GetDeviceFormFactorType() == DeviceFormFactorType.Phone)
                {
                    stepCounter = await StepCounter.GetDefaultAsync();

                    StepCount count = await stepCounter.GetStepCountForRangeAsync(DateTime.Now.Date, DateTime.Now - DateTime.Now.Date);

                    _steps = StepCountData.FromLumiaStepCount(count);
                }
                else
                {
                    var obj = await SenseRecording.LoadFromFileAsync("Simulations\\short recording.txt");

                    if (!await CallSensorCoreApiAsync(async() => {
                        stepCounter = await StepCounterSimulator.GetDefaultAsync(obj, DateTime.Now - TimeSpan.FromHours(12));
                        StepCount count = await stepCounter.GetStepCountForRangeAsync(DateTime.Now.Date, DateTime.Now - DateTime.Now.Date);
                        _steps = StepCountData.FromLumiaStepCount(count);
                    }))
                    {
                        return(false);
                    }
                }
            }
            catch (Exception e)
            {
                _lastError = SenseHelper.GetSenseError(e.HResult);
                return(false);
            }
            finally
            {
                if (stepCounter != null && typeof(StepCounter) == stepCounter.GetType())
                {
                    ((StepCounter)stepCounter).Dispose();
                }
            }
            return(true);
        }
        /// <summary>
        /// Invoked when 'GetCurrentButton' is clicked.
        /// 'ReadingChanged' will not be fired when there is no activity on the pedometer
        /// and hence can't be reliably used to get the current step count. This handler makes
        /// use of pedometer history on the system to get the current step count of the parameter
        /// </summary>
        async private void GetCurrentButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            DateTime dt             = DateTime.FromFileTimeUtc(0);
            int      totalStepCount = 0;
            int      lastTotalCount = 0;

            rootPage.NotifyUser("Retrieving history to get current step counts", NotifyType.StatusMessage);

            // Disable the button while we get the history
            GetCurrentButton.IsEnabled = false;

            DateTimeOffset fromBeginning = new DateTimeOffset(dt);

            IReadOnlyList <PedometerReading> historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning);


            // History always returns chronological list of step counts for all PedometerStepKinds
            // And each record represents cumulative step counts for that step kind.
            // So we will use the last set of records - that gives us the cumulative step count for
            // each kind and ignore rest of the records
            PedometerStepKind stepKind = PedometerStepKind.Unknown;
            DateTimeOffset    lastReadingTimestamp;
            bool resetTotal = false;

            foreach (PedometerReading reading in historyReadings)
            {
                if (stepKind == PedometerStepKind.Running)
                {
                    // reset the total after reading the 'PedometerStepKind.Running' count
                    resetTotal = true;
                }

                totalStepCount += reading.CumulativeSteps;
                if (resetTotal)
                {
                    lastReadingTimestamp = reading.Timestamp;
                    lastTotalCount       = totalStepCount;
                    stepKind             = PedometerStepKind.Unknown;
                    totalStepCount       = 0;
                    resetTotal           = false;
                }
                else
                {
                    stepKind++;
                }
            }

            ScenarioOutput_TotalStepCount.Text = lastTotalCount.ToString();

            DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime");

            ScenarioOutput_Timestamp.Text = timestampFormatter.Format(lastReadingTimestamp);

            rootPage.NotifyUser("Hit the 'Get steps count' Button", NotifyType.StatusMessage);
            GetCurrentButton.IsEnabled = true;
        }
示例#5
0
        /// <summary>
        /// Gets number of steps for current day
        /// </summary>
        /// <returns><c>true</c> if steps were successfully fetched, <c>false</c> otherwise</returns>
        private async Task <bool> GetStepsAsync()
        {
            // First try the pedometer
            try
            {
                var readings = await Pedometer.GetSystemHistoryAsync(DateTime.Now.Date, DateTime.Now - DateTime.Now.Date);

                _steps = StepCountData.FromPedometerReadings(readings);
                return(true);
            }
            catch (Exception)
            {
                // Continue to the fallback
            }

            // Fall back to using Lumia Sensor Core.
            StepCounter stepCounter = null;

            try
            {
                stepCounter = await StepCounter.GetDefaultAsync();

                StepCount count = await stepCounter.GetStepCountForRangeAsync(
                    DateTime.Now.Date,
                    DateTime.Now - DateTime.Now.Date);

                _steps = StepCountData.FromLumiaStepCount(count);
            }
            catch (Exception e)
            {
                _lastError = SenseHelper.GetSenseError(e.HResult);
                return(false);
            }
            finally
            {
                if (stepCounter != null)
                {
                    stepCounter.Dispose();
                }
            }
            return(true);
        }
示例#6
0
        public async Task <List <ReadingByDate> > GetStepsForHour(int hour, int days)
        {
            List <ReadingByDate> stepsByDay = new List <ReadingByDate>();

            for (int i = 0; i < days; i++)
            {
                var dateTime    = DateTime.Now.Subtract(TimeSpan.FromDays(i));
                var stepsForDay = await Pedometer.GetSystemHistoryAsync(dateTime, TimeSpan.FromHours(hour));

                var data = StepCountData.FromPedometerReadings(stepsForDay);
                stepsByDay.Add(new ReadingByDate
                {
                    DateTime          = dateTime.AddHours(hour),
                    RunningStepsCount = data.RunningCount,
                    WalkingStepsCount = data.WalkingCount,
                    TotalStepsCount   = data.TotalCount
                });
            }
            return(stepsByDay);
        }
        /// <summary>
        /// Invoked when 'Get History' button is clicked.
        /// Depending on the user selection, this handler uses one of the overloaded
        /// 'GetSystemHistoryAsync' APIs to retrieve the pedometer history of the user
        /// </summary>
        /// <param name="sender">unused</param>
        /// <param name="e">unused</param>
        async private void GetHistory_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            IReadOnlyList <PedometerReading> historyReadings = null;
            DateTimeFormatter timestampFormatter             = new DateTimeFormatter("shortdate longtime");

            // Disable subsequent history retrieval while the async operation is in progress
            GetHistory.IsEnabled = false;

            // clear previous content being displayed
            historyRecords.Clear();

            try
            {
                if (getAllHistory)
                {
                    DateTime       dt            = DateTime.FromFileTimeUtc(0);
                    DateTimeOffset fromBeginning = new DateTimeOffset(dt);
                    rootPage.NotifyUser("Retrieving all available History", NotifyType.StatusMessage);
                    historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning);
                }
                else
                {
                    String   notificationString = "Retrieving history from: ";
                    Calendar calendar           = new Calendar();
                    calendar.ChangeClock("24HourClock");

                    // DateTime picker will also include hour, minute and seconds from the the system time.
                    // Decrement the same to be able to correctly add TimePicker values.

                    calendar.SetDateTime(FromDate.Date);
                    calendar.AddNanoseconds(-calendar.Nanosecond);
                    calendar.AddSeconds(-calendar.Second);
                    calendar.AddMinutes(-calendar.Minute);
                    calendar.AddHours(-calendar.Hour);
                    calendar.AddSeconds(Convert.ToInt32(FromTime.Time.TotalSeconds));

                    DateTimeOffset fromTime = calendar.GetDateTime();

                    calendar.SetDateTime(ToDate.Date);
                    calendar.AddNanoseconds(-calendar.Nanosecond);
                    calendar.AddSeconds(-calendar.Second);
                    calendar.AddMinutes(-calendar.Minute);
                    calendar.AddHours(-calendar.Hour);
                    calendar.AddSeconds(Convert.ToInt32(ToTime.Time.TotalSeconds));

                    DateTimeOffset toTime = calendar.GetDateTime();

                    notificationString += timestampFormatter.Format(fromTime);
                    notificationString += " To ";
                    notificationString += timestampFormatter.Format(toTime);

                    if (toTime.ToFileTime() < fromTime.ToFileTime())
                    {
                        rootPage.NotifyUser("Invalid time span. 'To Time' must be equal or more than 'From Time'", NotifyType.ErrorMessage);

                        // Enable subsequent history retrieval while the async operation is in progress
                        GetHistory.IsEnabled = true;
                    }
                    else
                    {
                        TimeSpan span;
                        span = TimeSpan.FromTicks(toTime.Ticks - fromTime.Ticks);
                        rootPage.NotifyUser(notificationString, NotifyType.StatusMessage);
                        historyReadings = await Pedometer.GetSystemHistoryAsync(fromTime, span);
                    }
                }

                if (historyReadings != null)
                {
                    foreach (PedometerReading reading in historyReadings)
                    {
                        HistoryRecord record = new HistoryRecord(reading);
                        historyRecords.Add(record);
                    }

                    rootPage.NotifyUser("History retrieval completed", NotifyType.StatusMessage);
                }
            }
            catch (UnauthorizedAccessException)
            {
                rootPage.NotifyUser("User has denied access to activity history", NotifyType.ErrorMessage);
            }

            // Finally, re-enable history retrieval
            GetHistory.IsEnabled = true;
        }
        /// <summary>
        /// Invoked when 'GetCurrentButton' is clicked.
        /// 'ReadingChanged' will not be fired when there is no activity on the pedometer
        /// and hence can't be reliably used to get the current step count. This handler makes
        /// use of pedometer history on the system to get the current step count of the parameter
        /// </summary>
        async private void GetCurrentButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            // Determine if we can access pedometers
            var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(PedometerClassId);

            if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed)
            {
                // Determine if a pedometer is present
                // This can also be done using Windows::Devices::Enumeration::DeviceInformation::FindAllAsync
                var sensor = await Pedometer.GetDefaultAsync();

                if (sensor != null)
                {
                    DateTime dt             = DateTime.FromFileTimeUtc(0);
                    int      totalStepCount = 0;
                    int      lastTotalCount = 0;

                    rootPage.NotifyUser("Retrieving history to get current step counts", NotifyType.StatusMessage);

                    // Disable the button while we get the history
                    GetCurrentButton.IsEnabled = false;

                    DateTimeOffset fromBeginning = new DateTimeOffset(dt);

                    try
                    {
                        var historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning);

                        // History always returns chronological list of step counts for all PedometerStepKinds
                        // And each record represents cumulative step counts for that step kind.
                        // So we will use the last set of records - that gives us the cumulative step count for
                        // each kind and ignore rest of the records
                        PedometerStepKind stepKind = PedometerStepKind.Unknown;
                        DateTimeOffset    lastReadingTimestamp;
                        bool resetTotal = false;
                        foreach (PedometerReading reading in historyReadings)
                        {
                            if (stepKind == PedometerStepKind.Running)
                            {
                                // reset the total after reading the 'PedometerStepKind.Running' count
                                resetTotal = true;
                            }

                            totalStepCount += reading.CumulativeSteps;
                            if (resetTotal)
                            {
                                lastReadingTimestamp = reading.Timestamp;
                                lastTotalCount       = totalStepCount;
                                stepKind             = PedometerStepKind.Unknown;
                                totalStepCount       = 0;
                                resetTotal           = false;
                            }
                            else
                            {
                                stepKind++;
                            }
                        }

                        ScenarioOutput_TotalStepCount.Text = lastTotalCount.ToString();

                        DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime");
                        ScenarioOutput_Timestamp.Text = timestampFormatter.Format(lastReadingTimestamp);

                        rootPage.NotifyUser("Hit the 'Get steps count' Button", NotifyType.StatusMessage);
                    }
                    catch (UnauthorizedAccessException)
                    {
                        rootPage.NotifyUser("User has denied access to activity history", NotifyType.ErrorMessage);
                    }

                    // Re-enable button
                    GetCurrentButton.IsEnabled = true;
                }
                else
                {
                    rootPage.NotifyUser("No pedometers found", NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Access to pedometers is denied", NotifyType.ErrorMessage);
            }
        }
示例#9
0
        /// <summary>
        /// Invoked when 'Get History' button is clicked.
        /// Depending on the user selection, this handler uses one of the overloaded
        /// 'GetSystemHistoryAsync' APIs to retrieve the pedometer history of the user
        /// </summary>
        /// <param name="sender">unused</param>
        /// <param name="e">unused</param>
        async private void GetHistory_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            GetHistory.IsEnabled = false;

            // Determine if we can access pedometers
            var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(PedometerClassId);

            if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed)
            {
                // Determine if a pedometer is present
                // This can also be done using Windows::Devices::Enumeration::DeviceInformation::FindAllAsync
                var sensor = await Pedometer.GetDefaultAsync();

                if (sensor != null)
                {
                    IReadOnlyList <PedometerReading> historyReadings = null;
                    var timestampFormatter = new DateTimeFormatter("shortdate longtime");

                    // Disable subsequent history retrieval while the async operation is in progress
                    GetHistory.IsEnabled = false;

                    // clear previous content being displayed
                    historyRecords.Clear();

                    try
                    {
                        if (getAllHistory)
                        {
                            var dt            = DateTime.FromFileTimeUtc(0);
                            var fromBeginning = new DateTimeOffset(dt);
                            rootPage.NotifyUser("Retrieving all available History", NotifyType.StatusMessage);
                            historyReadings = await Pedometer.GetSystemHistoryAsync(fromBeginning);
                        }
                        else
                        {
                            String notificationString = "Retrieving history from: ";
                            var    calendar           = new Calendar();
                            calendar.ChangeClock("24HourClock");

                            // DateTime picker will also include hour, minute and seconds from the the system time.
                            // Decrement the same to be able to correctly add TimePicker values.

                            calendar.SetDateTime(FromDate.Date);
                            calendar.AddNanoseconds(-calendar.Nanosecond);
                            calendar.AddSeconds(-calendar.Second);
                            calendar.AddMinutes(-calendar.Minute);
                            calendar.AddHours(-calendar.Hour);
                            calendar.AddSeconds(Convert.ToInt32(FromTime.Time.TotalSeconds));

                            DateTimeOffset fromTime = calendar.GetDateTime();

                            calendar.SetDateTime(ToDate.Date);
                            calendar.AddNanoseconds(-calendar.Nanosecond);
                            calendar.AddSeconds(-calendar.Second);
                            calendar.AddMinutes(-calendar.Minute);
                            calendar.AddHours(-calendar.Hour);
                            calendar.AddSeconds(Convert.ToInt32(ToTime.Time.TotalSeconds));

                            DateTimeOffset toTime = calendar.GetDateTime();

                            notificationString += timestampFormatter.Format(fromTime);
                            notificationString += " To ";
                            notificationString += timestampFormatter.Format(toTime);

                            if (toTime.ToFileTime() < fromTime.ToFileTime())
                            {
                                rootPage.NotifyUser("Invalid time span. 'To Time' must be equal or more than 'From Time'", NotifyType.ErrorMessage);

                                // Enable subsequent history retrieval while the async operation is in progress
                                GetHistory.IsEnabled = true;
                            }
                            else
                            {
                                TimeSpan span = TimeSpan.FromTicks(toTime.Ticks - fromTime.Ticks);
                                rootPage.NotifyUser(notificationString, NotifyType.StatusMessage);
                                historyReadings = await Pedometer.GetSystemHistoryAsync(fromTime, span);
                            }
                        }

                        if (historyReadings != null)
                        {
                            foreach (PedometerReading reading in historyReadings)
                            {
                                HistoryRecord record = new HistoryRecord(reading);
                                historyRecords.Add(record);

                                // Get at most 100 records (number is arbitrary chosen for demonstration purposes)
                                if (historyRecords.Count == 100)
                                {
                                    break;
                                }
                            }

                            rootPage.NotifyUser("History retrieval completed", NotifyType.StatusMessage);
                        }
                    }
                    catch (UnauthorizedAccessException)
                    {
                        rootPage.NotifyUser("User has denied access to activity history", NotifyType.ErrorMessage);
                    }

                    // Finally, re-enable history retrieval
                    GetHistory.IsEnabled = true;
                }
                else
                {
                    rootPage.NotifyUser("No pedometers found", NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Access to pedometers is denied", NotifyType.ErrorMessage);
            }
        }