private Task <bool> CheckSensors()
        {
            // Determine if the user has allowed access to activity sensors
            var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(new Guid("9D9E0118-1807-4F2E-96E4-2CE57142E196"));

            return(Task.FromResult(deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed));
        }
Exemple #2
0
        private async void EnableActivityDetectionAsync()
        {
            var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(ActivitySensorClassId);

            // Determine if we can access activity sensors
            if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed)
            {
                if (activitySensor == null)
                {
                    activitySensor = await ActivitySensor.GetDefaultAsync();
                }

                if (activitySensor != null)
                {
                    activitySensor.SubscribedActivities.Add(ActivityType.Walking);
                    activitySensor.SubscribedActivities.Add(ActivityType.Running);
                    activitySensor.SubscribedActivities.Add(ActivityType.Fidgeting);
                    activitySensor.SubscribedActivities.Add(ActivityType.Stationary);


                    activitySensor.ReadingChanged += new TypedEventHandler <ActivitySensor, ActivitySensorReadingChangedEventArgs>(ReadingChanged);

                    Status.Text = "Subscribed to reading changes";
                }
                else
                {
                    Status.Text = "No activity sensor found";
                }
            }
            else
            {
                Status.Text = "Access denied to activity sensors";
            }
        }
Exemple #3
0
        /// <summary>
        /// This is the click handler for the 'Register Task' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void ScenarioRegisterTask(object sender, RoutedEventArgs e)
        {
            // Determine if we can access activity sensors
            var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(ActivitySensorClassId);

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

                if (activitySensor != 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 activity sensors found", NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Access denied to activity sensors", NotifyType.ErrorMessage);
            }
        }
Exemple #4
0
        public async void RegisterActivityTriggerTask()
        {
            var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(new Guid("9D9E0118-1807-4F2E-96E4-2CE57142E196"));

            if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed)
            {
                if (!BackgroundTaskRegistration.AllTasks.Any(p => p.Value.Name == nameof(ActivityTask)))
                {
                    var builder = new BackgroundTaskBuilder
                    {
                        Name           = nameof(ActivityTask),
                        TaskEntryPoint = typeof(ActivityTask).FullName
                    };
                    var trigger = new ActivitySensorTrigger((uint)new TimeSpan(0, 5, 0).TotalMilliseconds);
                    foreach (var act in trigger.SupportedActivities)
                    {
                        trigger.SubscribedActivities.Add(act);
                    }
                    builder.SetTrigger(trigger);
                    BackgroundTaskRegistration t = builder.Register();
                    await client.LogAsync($"Successfully registered activity trigger task.", 1);
                }
            }
            else
            {
                await client.LogAsync($"Activity Sensor not allowed", 3);
            }
        }
        /// <summary>
        /// Determines whether this instance has permission the specified permission.
        /// </summary>
        /// <returns><c>true</c> if this instance has permission the specified permission; otherwise, <c>false</c>.</returns>
        /// <param name="permission">Permission to check.</param>
        public Task <PermissionStatus> CheckPermissionStatusAsync(Permission permission)
        {
            switch (permission)
            {
            case Permission.Calendar:
                break;

            case Permission.Camera:
                break;

            case Permission.Contacts:
                return(CheckContactsAsync());

            case Permission.Location:
            case Permission.LocationAlways:
            case Permission.LocationWhenInUse:
                return(CheckLocationAsync());

            case Permission.Microphone:
                break;

            case Permission.Phone:
                break;

            case Permission.Photos:
                break;

            case Permission.Reminders:
                break;

            case Permission.Sensors:
            {
                // Determine if the user has allowed access to activity sensors
                var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(ActivitySensorClassId);
                switch (deviceAccessInfo.CurrentStatus)
                {
                case DeviceAccessStatus.Allowed:
                    return(Task.FromResult(PermissionStatus.Granted));

                case DeviceAccessStatus.DeniedBySystem:
                case DeviceAccessStatus.DeniedByUser:
                    return(Task.FromResult(PermissionStatus.Denied));

                default:
                    return(Task.FromResult(PermissionStatus.Unknown));
                }
            }

            case Permission.Sms:
                break;

            case Permission.Storage:
                break;

            case Permission.Speech:
                break;
            }
            return(Task.FromResult(PermissionStatus.Granted));
        }
        public Scenario1_Events()
        {
            this.InitializeComponent();

            // Register for access changed notifications for pedometers
            deviceAccessInformation = DeviceAccessInformation.CreateFromDeviceClassId(PedometerClassId);
            deviceAccessInformation.AccessChanged += new TypedEventHandler <DeviceAccessInformation, DeviceAccessChangedEventArgs>(AccessChanged);
        }
        public Scenario3_ChangeEvents()
        {
            this.InitializeComponent();
            _activitySensor = null;

            // Register for access changed notifications for activity sensors
            _deviceAccessInformation = DeviceAccessInformation.CreateFromDeviceClassId(ActivitySensorClassId);
            _deviceAccessInformation.AccessChanged += new TypedEventHandler <DeviceAccessInformation, DeviceAccessChangedEventArgs>(AccessChanged);
        }
Exemple #8
0
        /// <summary>
        /// This is the click handler for the 'Get Activity History' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void ScenarioGetActivityHistory(object sender, RoutedEventArgs e)
        {
            // Reset fields and status
            ScenarioOutput_Count.Text       = "No data";
            ScenarioOutput_Activity1.Text   = "No data";
            ScenarioOutput_Confidence1.Text = "No data";
            ScenarioOutput_Timestamp1.Text  = "No data";
            ScenarioOutput_ActivityN.Text   = "No data";
            ScenarioOutput_ConfidenceN.Text = "No data";
            ScenarioOutput_TimestampN.Text  = "No data";
            rootPage.NotifyUser("", NotifyType.StatusMessage);

            // Determine if we can access activity sensors
            var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(ActivitySensorClassId);

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

                if (activitySensor != null)
                {
                    var calendar = new Calendar();
                    calendar.SetToNow();
                    calendar.AddDays(-1);
                    var yesterday = calendar.GetDateTime();

                    // Get history from yesterday onwards
                    var history = await ActivitySensor.GetSystemHistoryAsync(yesterday);

                    ScenarioOutput_Count.Text = history.Count.ToString();
                    if (history.Count > 0)
                    {
                        var reading1 = history[0];
                        ScenarioOutput_Activity1.Text   = reading1.Activity.ToString();
                        ScenarioOutput_Confidence1.Text = reading1.Confidence.ToString();
                        ScenarioOutput_Timestamp1.Text  = reading1.Timestamp.ToString("u");

                        var readingN = history[history.Count - 1];
                        ScenarioOutput_ActivityN.Text   = readingN.Activity.ToString();
                        ScenarioOutput_ConfidenceN.Text = readingN.Confidence.ToString();
                        ScenarioOutput_TimestampN.Text  = readingN.Timestamp.ToString("u");
                    }
                }
                else
                {
                    rootPage.NotifyUser("No activity sensors found", NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Access to activity sensors is denied", NotifyType.ErrorMessage);
            }
        }
        /// <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);
            }
        }
        public Scenario2_Polling()
        {
            String customSensorSelector = "";

            this.InitializeComponent();

            customSensorSelector = CustomSensor.GetDeviceSelector(GUIDCustomSensorDeviceVendorDefinedTypeID);
            watcher        = DeviceInformation.CreateWatcher(customSensorSelector);
            watcher.Added += OnCustomSensorAdded;
            watcher.Start();

            // Register to be notified when the user disables access to the custom sensor through privacy settings.
            deviceAccessInformation = DeviceAccessInformation.CreateFromDeviceClassId(GUIDCustomSensorDeviceVendorDefinedTypeID);
            deviceAccessInformation.AccessChanged += new TypedEventHandler <DeviceAccessInformation, DeviceAccessChangedEventArgs>(OnAccessChanged);
        }
            public override Task <PermissionStatus> CheckStatusAsync()
            {
                // Determine if the user has allowed access to activity sensors
                var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(activitySensorClassId);

                switch (deviceAccessInfo.CurrentStatus)
                {
                case DeviceAccessStatus.Allowed:
                    return(Task.FromResult(PermissionStatus.Granted));

                case DeviceAccessStatus.DeniedBySystem:
                case DeviceAccessStatus.DeniedByUser:
                    return(Task.FromResult(PermissionStatus.Denied));

                default:
                    return(Task.FromResult(PermissionStatus.Unknown));
                }
            }
Exemple #12
0
        /// <summary>
        /// This is the click handler for the 'Get Current Activity' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void ScenarioGetCurrentActivity(object sender, RoutedEventArgs e)
        {
            // Reset fields and status
            ScenarioOutput_Activity.Text   = "No data";
            ScenarioOutput_Confidence.Text = "No data";
            ScenarioOutput_Timestamp.Text  = "No data";
            rootPage.NotifyUser("", NotifyType.StatusMessage);

            // Determine if we can access activity sensors
            var deviceAccessInfo = DeviceAccessInformation.CreateFromDeviceClassId(ActivitySensorClassId);

            if (deviceAccessInfo.CurrentStatus == DeviceAccessStatus.Allowed)
            {
                // Get the default sensor
                var activitySensor = await ActivitySensor.GetDefaultAsync();

                if (activitySensor != null)
                {
                    // Get the current activity reading
                    var reading = await activitySensor.GetCurrentReadingAsync();

                    if (reading != null)
                    {
                        ScenarioOutput_Activity.Text   = reading.Activity.ToString();
                        ScenarioOutput_Confidence.Text = reading.Confidence.ToString();
                        ScenarioOutput_Timestamp.Text  = reading.Timestamp.ToString("u");
                    }
                }
                else
                {
                    rootPage.NotifyUser("No activity sensor found", NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Access denied to activity sensors", NotifyType.ErrorMessage);
            }
        }
        /// <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);
            }
        }
Exemple #14
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);
            }
        }