/// <summary>
        /// Invoked when 'Register Task' button is clicked. Attempts to find a default
        /// Pedometer and registers a background task with a step goal of 50 steps.
        /// Adds a
        /// </summary>
        private async void ScenarioRegisterTask_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
        {
            try
            {
                sensor = await Pedometer.GetDefaultAsync();

                if (sensor != null)
                {
                    var status = await BackgroundExecutionManager.RequestAccessAsync();

                    if ((BackgroundAccessStatus.AllowedWithAlwaysOnRealTimeConnectivity == status) ||
                        (BackgroundAccessStatus.AllowedMayUseActiveRealTimeConnectivity == status))
                    {
                        RegisterBackgroundTask();
                    }
                    else
                    {
                        rootPage.NotifyUser("Background tasks may be disabled for this app", NotifyType.ErrorMessage);
                    }
                }
                else
                {
                    rootPage.NotifyUser("No pedometer sensors found", NotifyType.ErrorMessage);
                }
            }
            catch (UnauthorizedAccessException)
            {
                rootPage.NotifyUser("User has denied access to Pedometer history", NotifyType.ErrorMessage);
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// 'Register ReadingChanged' button click handler. Registers to the '
        /// ReadingChanged' event of the default pedometer opened earlier.
        /// </summary>
        /// <param name="sender">unused</param>
        /// <param name="e">unused</param>
        async private void RegisterButton_Click(object sender, RoutedEventArgs e)
        {
            // Get the default sensor
            if (!registeredForEvents)
            {
                RegisterButton.IsEnabled = false;
                try
                {
                    pedometer = await Pedometer.GetDefaultAsync();

                    if (pedometer == null)
                    {
                        rootPage.NotifyUser("No pedometer available", NotifyType.ErrorMessage);
                    }
                    RegisterButton.Content   = "UnRegister ReadingChanged";
                    RegisterButton.IsEnabled = true;
                    rootPage.NotifyUser("Registered for step count changes", NotifyType.StatusMessage);
                }
                catch (System.UnauthorizedAccessException)
                {
                    rootPage.NotifyUser("Access to the default pedometer is denied", NotifyType.ErrorMessage);
                }
                pedometer.ReadingChanged += Pedometer_ReadingChanged;
                registeredForEvents       = true;
            }
            else
            {
                pedometer.ReadingChanged -= Pedometer_ReadingChanged;
                pedometer = null;
                RegisterButton.Content = "Register ReadingChanged";
                registeredForEvents    = false;
                rootPage.NotifyUser("Pedometer available - Not registered for events", NotifyType.StatusMessage);
            }
        }
Ejemplo n.º 3
0
        public async void StartReading(int reportInterval = -1)
        {
            _pedometer = await Pedometer.GetDefaultAsync();

            if (reportInterval >= 0)
            {
                _pedometer.ReportInterval = (uint)reportInterval;
            }

            _pedometer.ReadingChanged += PedometerReadingChanged;
        }
Ejemplo n.º 4
0
        /// <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 'GetCurrentReadings' API to determine the current step count
        /// </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;

                    // Get the current readings to find the current step counters
                    var  currentReadings = sensor.GetCurrentReadings();
                    bool updateTimestamp = true;
                    foreach (PedometerStepKind kind in Enum.GetValues(typeof(PedometerStepKind)))
                    {
                        PedometerReading reading;
                        if (currentReadings.TryGetValue(kind, out reading))
                        {
                            totalStepCount += reading.CumulativeSteps;
                        }
                        if (updateTimestamp)
                        {
                            DateTimeFormatter timestampFormatter = new DateTimeFormatter("shortdate longtime");
                            ScenarioOutput_Timestamp.Text = timestampFormatter.Format(reading.Timestamp);
                            updateTimestamp = false;
                        }
                    }

                    ScenarioOutput_TotalStepCount.Text = totalStepCount.ToString();
                    rootPage.NotifyUser("Hit the 'Get steps count' Button", NotifyType.StatusMessage);

                    // Re-enable button
                    GetCurrentButton.IsEnabled = true;
                }
                else
                {
                    rootPage.NotifyUser("No pedometers found", NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Access to pedometers is denied", NotifyType.ErrorMessage);
            }
        }
Ejemplo n.º 5
0
        // <summary>
        // Background task entry point.
        // </summary>
        // <param name="taskInstance"></param>
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            //alti = Altimeter.GetDefault();
            high = Altimeter.GetDefault();
            if (null != high)
            {
                TimerCallback timerc = new TimerCallback(timerTask);
                timer = new Timer(timerc, null, 1000 * 60 * 10, 1000 * 60 * 10);

                dm = DataManager.getInstance();
                //dm.setHeightTable();
                //IAsyncOperation<Pedometer> iasyncP = Pedometer.GetDefaultAsync();
                pressure = Barometer.GetDefault();

                // Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
                //uint minReportIntervalMsecs = alti.MinimumReportInterval;
                //alti.ReportInterval = 50000;

                // Subscribe to accelerometer ReadingChanged events.
                //initAlti = alti.GetCurrentReading().AltitudeChangeInMeters;
                //barometer = Barometer.GetDefault();
                //barometer.ReportInterval = 2000;
                //initBarometer = barometer.GetCurrentReading().StationPressureInHectopascals;
                //barometer.ReadingChanged += new TypedEventHandler<Barometer, BarometerReadingChangedEventArgs>(Barometer_Readingchanged);

                // Take a deferral that is released when the task is completed.
                _deferral = taskInstance.GetDeferral();
                // Get notified when the task is canceled.
                taskInstance.Canceled += new BackgroundTaskCanceledEventHandler(OnCanceled);
                //Task.Delay(500).Wait();
                // Store a setting so that the app knows that the task is running.
                //ApplicationData.Current.LocalSettings.Values["IsBackgroundTaskActive"] = true;
                //pedometer = iasyncP.GetResults();
                pedometer = await Pedometer.GetDefaultAsync();

                start();
                high.ReadingChanged      += new TypedEventHandler <Altimeter, AltimeterReadingChangedEventArgs>(ReadingChanged);
                pedometer.ReadingChanged += new TypedEventHandler <Pedometer, PedometerReadingChangedEventArgs>(Pedometer_ReadingChanged);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Static method to get the default steps engine present in the system.
        /// </summary>
        public static async Task <IStepsEngine> GetDefaultAsync()
        {
            IStepsEngine stepsEngine = null;

            try
            {
                // Check if there is a pedometer in the system.
                // This also checks if the user has disabled motion data from Privacy settings
                Pedometer pedometer = await Pedometer.GetDefaultAsync();

                // If there is one then create OSStepsEngine.
                if (pedometer != null)
                {
                    stepsEngine = new OSStepsEngine();
                }
            }
            catch (System.UnauthorizedAccessException)
            {
                // If there is a pedometer but the user has disabled motion data
                // then check if the user wants to open settngs and enable motion data.
                MessageDialog dialog = new MessageDialog("Motion access has been disabled in system settings. Do you want to open settings now?", "Information");
                dialog.Commands.Add(new UICommand("Yes", async cmd => await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-motion"))));
                dialog.Commands.Add(new UICommand("No"));
                await dialog.ShowAsync();

                new System.Threading.ManualResetEvent(false).WaitOne(500);
                return(null);
            }

            // No Windows.Devices.Sensors.Pedometer exists, fall back to using Lumia Sensor Core.
            if (stepsEngine == null)
            {
                // Check if all the required settings have been configured correctly
                await LumiaStepsEngine.ValidateSettingsAsync();

                stepsEngine = new LumiaStepsEngine();
            }
            return(stepsEngine);
        }
Ejemplo n.º 7
0
        private async void end(string name)
        {
            DataManager dm       = DataManager.getInstance();
            var         settings = ApplicationData.Current.LocalSettings;
            double      nowH     = (double)settings.Values["nowH"];
            int         startRS  = (int)settings.Values["startRS"];
            int         startWS  = (int)settings.Values["startWS"];
            var         aaa      = await Pedometer.GetDefaultAsync();

            var    aa = aaa.GetCurrentReadings();
            int    rs = aa[PedometerStepKind.Running].CumulativeSteps;
            int    ws = aa[PedometerStepKind.Walking].CumulativeSteps;
            double p  = Barometer.GetDefault().GetCurrentReading().StationPressureInHectopascals;
            double h  = Math.Round(nowH, 1);
            double la = 200;
            double lo = 200;

            try
            {
                Geolocator geolocator = new Geolocator();
                // 获取当前的位置
                Geoposition pos = await geolocator.GetGeopositionAsync();

                //纬度
                la = pos.Coordinate.Point.Position.Latitude;
                //经度
                lo = pos.Coordinate.Point.Position.Longitude;
            }
            catch (UnauthorizedAccessException)
            {
                //未授权的访问异常
            }
            catch (Exception ex)
            {
                //超时 time out
            }
            dm.end(la, lo, h, p, ws, rs, (ws - startWS) + (rs - startRS), name);
            dm.closeDB();
        }
        /// <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);
            }
        }
Ejemplo n.º 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);
            }
        }