/// <summary>
        /// This is the click handler for the 'Reading Changed On' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ScenarioEnableReadingChanged(object sender, RoutedEventArgs e)
        {
            // Determine if we can access activity sensors
            if (_deviceAccessInformation.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.InVehicle);
                    _activitySensor.SubscribedActivities.Add(ActivityType.Biking);
                    _activitySensor.SubscribedActivities.Add(ActivityType.Fidgeting);

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

                    ScenarioEnableReadingChangedButton.IsEnabled  = false;
                    ScenarioDisableReadingChangedButton.IsEnabled = true;
                    rootPage.NotifyUser("Subscribed to reading changes", NotifyType.StatusMessage);
                }
                else
                {
                    rootPage.NotifyUser("No activity sensor found", NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Access denied to activity sensors", NotifyType.ErrorMessage);
            }
        }
Ejemplo n.º 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";
            }
        }
        /// <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);

            // Get the default sensor
            var activitySensor = await ActivitySensor.GetDefaultAsync();

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

                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);
            }
        }
Ejemplo n.º 4
0
        async void OnLoaded(object sender, RoutedEventArgs e)
        {
            this.DataContext = this;

            // We should check that we have access to this sensor really rather
            // than just going for it as we do here.
            this.activitySensor = await ActivitySensor.GetDefaultAsync();

            if (this.activitySensor != null)
            {
                var reading = await this.activitySensor.GetCurrentReadingAsync();

                if (reading != null)
                {
                    this.DisplayReading(reading);
                }
                // Subscribe to all the activities that the sensor supports.
                foreach (var activityType in Enum.GetValues(typeof(ActivityType)))
                {
                    if (this.activitySensor.SupportedActivities.Contains((ActivityType)activityType))
                    {
                        this.activitySensor.SubscribedActivities.Add((ActivityType)activityType);
                    }
                }
                // Wait for new values to come through.
                this.activitySensor.ReadingChanged += OnReadingChanged;

                // Get the history for the past week
                var history = await ActivitySensor.GetSystemHistoryAsync(
                    DateTimeOffset.Now - TimeSpan.FromDays(7));

                this.ActivityHistory = new ObservableCollection <ActivitySensorReading>(
                    history);
            }
        }
        /// <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);

            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");
            }
        }
        /// <summary>
        /// This is the click handler for the 'Reading Changed On' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void ScenarioEnableReadingChanged(object sender, RoutedEventArgs e)
        {
            if (null == _activitySensor)
            {
                _activitySensor = await ActivitySensor.GetDefaultAsync();
            }

            if (_activitySensor)
            {
                _activitySensor.SubscribedActivities.Add(ActivityType.Walking);
                _activitySensor.SubscribedActivities.Add(ActivityType.Running);
                _activitySensor.SubscribedActivities.Add(ActivityType.InVehicle);
                _activitySensor.SubscribedActivities.Add(ActivityType.Biking);
                _activitySensor.SubscribedActivities.Add(ActivityType.Fidgeting);

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

                ScenarioEnableReadingChangedButton.IsEnabled  = false;
                ScenarioDisableReadingChangedButton.IsEnabled = true;
            }
            else
            {
                rootPage.NotifyUser("No activity sensor found", NotifyType.ErrorMessage);
            }
        }
Ejemplo n.º 7
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);
            }
        }
Ejemplo n.º 8
0
        /// <summary>
        /// This is the click handler for the 'Status Changed On' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void ScenarioEnableStatusChanged(object sender, RoutedEventArgs e)
        {
            try
            {
                if (null == _activitySensor)
                {
                    _activitySensor = await ActivitySensor.GetDefaultAsync();
                }

                if (null != _activitySensor)
                {
                    _activitySensor.StatusChanged += new TypedEventHandler <ActivitySensor, ActivitySensorStatusChangedEventArgs>(StatusChanged);

                    ScenarioEnableStatusChangedButton.IsEnabled  = false;
                    ScenarioDisableStatusChangedButton.IsEnabled = true;
                }
                else
                {
                    rootPage.NotifyUser("No activity sensor found", NotifyType.ErrorMessage);
                }
            }
            catch (UnauthorizedAccessException)
            {
                rootPage.NotifyUser("User has denied access to the activity sensor", NotifyType.ErrorMessage);
            }
        }
        public ActivityStateTrigger()
        {
            var watcher = DeviceInformation.CreateWatcher(ActivitySensor.GetDeviceSelector());

            watcher.Added   += OnActivitySensorAddedAsync;
            watcher.Removed += OnActivitySensorRemoved;
            watcher.Start();
        }
Ejemplo n.º 10
0
        public List <DeviceInfo> CreateList()
        {
            List <DeviceInfo> selectors = new List <DeviceInfo>();

            // Pre-canned device class selectors
            selectors.Add(new DeviceInfo()
            {
                DisplayName = "All Device Interfaces (default)", DeviceClassSelector = DeviceClass.All, Selection = null
            });
            selectors.Add(new DeviceInfo()
            {
                DisplayName = "Audio Capture", DeviceClassSelector = DeviceClass.AudioCapture, Selection = null
            });
            selectors.Add(new DeviceInfo()
            {
                DisplayName = "Audio Render", DeviceClassSelector = DeviceClass.AudioRender, Selection = null
            });
            selectors.Add(new DeviceInfo()
            {
                DisplayName = "Image Scanner", DeviceClassSelector = DeviceClass.ImageScanner, Selection = null
            });
            selectors.Add(new DeviceInfo()
            {
                DisplayName = "Location", DeviceClassSelector = DeviceClass.Location, Selection = null
            });
            selectors.Add(new DeviceInfo()
            {
                DisplayName = "Portable Storage", DeviceClassSelector = DeviceClass.PortableStorageDevice, Selection = null
            });
            selectors.Add(new DeviceInfo()
            {
                DisplayName = "Video Capture", DeviceClassSelector = DeviceClass.VideoCapture, Selection = null
            });

            // A few examples of selectors built dynamically by windows runtime apis.
            selectors.Add(new DeviceInfo()
            {
                DisplayName = "Human Interface (HID)", Selection = HidDevice.GetDeviceSelector(0, 0)
            });
            selectors.Add(new DeviceInfo()
            {
                DisplayName = "Activity Sensor", Selection = ActivitySensor.GetDeviceSelector()
            });
            selectors.Add(new DeviceInfo()
            {
                DisplayName = "Pedometer", Selection = Pedometer.GetDeviceSelector()
            });
            selectors.Add(new DeviceInfo()
            {
                DisplayName = "Proximity", Selection = ProximityDevice.GetDeviceSelector()
            });
            selectors.Add(new DeviceInfo()
            {
                DisplayName = "Proximity Sensor", Selection = ProximitySensor.GetDeviceSelector()
            });

            return(selectors);
        }
        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);
        }
Ejemplo n.º 12
0
        private async void ReadingChanged(ActivitySensor sender, ActivitySensorReadingChangedEventArgs args)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                ActivitySensorReading reading = args.Reading;

                SendMessage(reading.Activity.ToString());
            });
        }
        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);
        }
Ejemplo n.º 14
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 the device watcher detects that the activity sensor was removed.
        /// </summary>
        /// <param name="sender">The device watcher.</param>
        /// <param name="device">The device that was removed.</param>
        private void OnActivitySensorRemoved(DeviceWatcher sender, DeviceInformationUpdate device)
        {
            if ((this.activitySensor != null) && (this.activitySensor.DeviceId == device.Id))
            {
                this.activitySensor.ReadingChanged         -= ActivitySensor_ReadingChangedAsync;
                this.deviceAccessInformation.AccessChanged -= DeviceAccessInfo_AccessChangedAsync;
                this.activitySensor = null;

                SetActive(false);
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// OSActivitySensor constructor.
        /// </summary
        public OSActivitySensor(ActivitySensor sensor)
        {
            _sensor = sensor;
            // Using this method to detect if the application runs in the emulator or on a real device. Later the *Simulator API is used to read fake sense data on emulator.
            // In production code you do not need this and in fact you should ensure that you do not include the Lumia.Sense.Test reference in your project.
            EasClientDeviceInformation x = new EasClientDeviceInformation();

            if (x.SystemProductName.StartsWith("Virtual"))
            {
                _runningInEmulator = true;
            }
        }
Ejemplo n.º 17
0
 async void OnReadingChanged(ActivitySensor sender,
                             ActivitySensorReadingChangedEventArgs args)
 {
     await this.Dispatcher.RunAsync(
         CoreDispatcherPriority.Normal,
         () =>
     {
         if (args.Reading != null)
         {
             this.DisplayReading(args.Reading);
         }
     }
         );
 }
        /// <summary>
        /// Invoked when ActivitySensor reading changed event gets raised.
        /// </summary>
        ///<param name="sender"></param>
        ///<param name="args"></param>
        private async void ActivitySensor_ReadingChangedAsync(ActivitySensor sender, ActivitySensorReadingChangedEventArgs args)
        {
            var isActive = false;
            var reading  = args.Reading;

            if (reading != null)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    isActive = (reading.Activity == this.ActivityType) && (reading.Confidence >= this.ActivityReadingConfidence);
                });
            }

            SetActive(isActive);
        }
        /// <summary>
        /// Invoked when ActivitySensor reading changed event gets raised.
        /// </summary>
        ///<param name="sender"></param>
        ///<param name="args"></param>
        private async void ActivitySensor_ReadingChangedAsync(ActivitySensor sender, ActivitySensorReadingChangedEventArgs args)
        {
            var isActive = false;
            var reading = args.Reading;

            if (reading != null)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    isActive = (reading.Activity == this.ActivityType) && (reading.Confidence >= this.ActivityReadingConfidence);
                });
            }

            SetActive(isActive);
        }
        /// <summary>
        /// Invoked when the device watcher detects that the activity sensor was added.
        /// </summary>
        /// <param name="sender">The device watcher.</param>
        /// <param name="device">The device that was added.</param>
        private async void OnActivitySensorAddedAsync(DeviceWatcher sender, DeviceInformation device)
        {
            if (this.activitySensor == null)
            {
                var addedSensor = await ActivitySensor.FromIdAsync(device.Id);

                if (addedSensor != null)
                {
                    this.activitySensor = addedSensor;

                    this.deviceAccessInformation = DeviceAccessInformation.CreateFromId(this.activitySensor.DeviceId);
                    this.deviceAccessInformation.AccessChanged += DeviceAccessInfo_AccessChangedAsync;
                }
            }
        }
        /// <summary>
        /// This is the event handler for AccessChanged events.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void AccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs e)
        {
            var status = e.Status;

            if (status != DeviceAccessStatus.Allowed)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    rootPage.NotifyUser("Access denied to activity sensors", NotifyType.ErrorMessage);
                    _activitySensor = null;

                    ScenarioEnableReadingChangedButton.IsEnabled  = true;
                    ScenarioDisableReadingChangedButton.IsEnabled = false;
                });
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Returns the activity at the given time
        /// </summary>
        /// <param name="sensor">Sensor instance</param>
        /// <param name="timestamp">Time stamp</param>
        /// <returns>Activity at the given time or <c>null</c> if no activity is found.</returns>
        public static async Task <ActivitySensorReading> GetActivityAtAsync(DateTimeOffset timestamp)
        {
            // We assume here that one day overshoot is enough to cover most cases. If the previous activity lasted longer
            // than that, we will miss it. Overshoot duration can be extended but will decrease performance.
            TimeSpan overshoot = TimeSpan.FromDays(1);
            IReadOnlyList <ActivitySensorReading> history = await ActivitySensor.GetSystemHistoryAsync(
                timestamp - overshoot,
                overshoot);

            if (history.Count > 0)
            {
                return(history[history.Count - 1]);
            }
            else
            {
                return(null);
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Static method to get the default activity sensor present in the system.
        /// </summary>
        public static async Task <IActivitySensor> GetDefaultAsync()
        {
            IActivitySensor sensor = null;

            try
            {
                // Check if there is an activity sensor in the system
                ActivitySensor activitySensor = await ActivitySensor.GetDefaultAsync();

                // If there is one then create OSActivitySensor.
                if (activitySensor != null)
                {
                    sensor = new OSActivitySensor(activitySensor);
                }
            }
            catch (System.UnauthorizedAccessException)
            {
                // If there is an activity sensor 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);
            }

            // If the OS activity sensor is not present then create the LumiaActivitySensor.
            // This will use ActivityMonitor from SensorCore.
            if (sensor == null)
            {
                // Check if all the required settings have been configured correctly
                await LumiaActivitySensor.ValidateSettingsAsync();

                sensor = new LumiaActivitySensor();
            }
            return(sensor);
        }
Ejemplo n.º 24
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);
            }
        }
 public Scenario3_ChangeEvents()
 {
     this.InitializeComponent();
     _activitySensor = null;
 }
        /// <summary>
        /// Invoked when the device watcher detects that the activity sensor was added.
        /// </summary>
        /// <param name="sender">The device watcher.</param>
        /// <param name="device">The device that was added.</param>
        private async void OnActivitySensorAddedAsync(DeviceWatcher sender, DeviceInformation device)
        {
            if (this.activitySensor == null)
            {
                var addedSensor = await ActivitySensor.FromIdAsync(device.Id);

                if (addedSensor != null)
                {
                    this.activitySensor = addedSensor;

                    this.deviceAccessInformation = DeviceAccessInformation.CreateFromId(this.activitySensor.DeviceId);
                    this.deviceAccessInformation.AccessChanged += DeviceAccessInfo_AccessChangedAsync;
                }
            }
        }
        /// <summary>
        /// Invoked when the device watcher detects that the activity sensor was removed.
        /// </summary>
        /// <param name="sender">The device watcher.</param>
        /// <param name="device">The device that was removed.</param>
        private void OnActivitySensorRemoved(DeviceWatcher sender, DeviceInformationUpdate device)
        {
            if ((this.activitySensor != null) && (this.activitySensor.DeviceId == device.Id))
            {
                this.activitySensor.ReadingChanged -= ActivitySensor_ReadingChangedAsync;
                this.deviceAccessInformation.AccessChanged -= DeviceAccessInfo_AccessChangedAsync;
                this.activitySensor = null;

                SetActive(false);
            }
        }
Ejemplo n.º 28
0
 /// <summary>
 /// OSActivitySensor constructor.
 /// </summary
 public OSActivitySensor(ActivitySensor sensor)
 {
     _sensor = sensor;
     // Using this method to detect if the application runs in the emulator or on a real device. Later the *Simulator API is used to read fake sense data on emulator. 
     // In production code you do not need this and in fact you should ensure that you do not include the Lumia.Sense.Test reference in your project.
     EasClientDeviceInformation x = new EasClientDeviceInformation();
     if (x.SystemProductName.StartsWith("Virtual"))
     {
         _runningInEmulator = true;
     }
 }
Ejemplo n.º 29
0
        /// <summary>
        /// Updates the summary in the screen.
        /// </summary>
        /// <returns>Asynchronous task/returns>
        /// <param name="DayOffset">Day offset</param>
        /// <returns>Asyncrhonous Task</returns>
        public async Task UpdateSummaryAsync(uint DayOffset)
        {
            // Read current activity
            ActivitySensorReading reading = await _sensor.GetCurrentReadingAsync();

            if (reading != null)
            {
                ActivityData <Windows.Devices.Sensors.ActivityType> .Instance().CurrentActivity = reading.Activity;
            }

            // Fetch activity history for the day
            DateTime startDate = DateTime.Today.Subtract(TimeSpan.FromDays(DayOffset));
            DateTime endDate   = startDate + TimeSpan.FromDays(1);

            var history = await ActivitySensor.GetSystemHistoryAsync(startDate, TimeSpan.FromDays(1));

            // Create a dictionary to store data
            Dictionary <Windows.Devices.Sensors.ActivityType, TimeSpan> activitySummary = new Dictionary <Windows.Devices.Sensors.ActivityType, TimeSpan>();

            // Initialize timespan for all entries
            var activityTypes = Enum.GetValues(typeof(Windows.Devices.Sensors.ActivityType));

            foreach (var type in activityTypes)
            {
                activitySummary[(Windows.Devices.Sensors.ActivityType)type] = TimeSpan.Zero;
            }

            if (history.Count == 0 || history[0].Timestamp > startDate)
            {
                ActivitySensorReading firstReading = await GetActivityAtAsync(startDate);

                if (firstReading != null)
                {
                    List <ActivitySensorReading> finalHistory = new List <ActivitySensorReading>(history);
                    finalHistory.Insert(0, firstReading);
                    history = finalHistory.AsReadOnly();
                }
            }

            // Update the timespan for all activities in the dictionary
            if (history.Count > 0)
            {
                Windows.Devices.Sensors.ActivityType currentActivity = history[0].Activity;
                DateTime currentDate = history[0].Timestamp.DateTime;
                foreach (var item in history)
                {
                    if (item.Timestamp >= startDate)
                    {
                        TimeSpan duration = TimeSpan.Zero;
                        if (currentDate < startDate)
                        {
                            // If first activity of the day started already yesterday, set start time to midnight.
                            currentDate = startDate;
                        }
                        if (item.Timestamp > endDate)
                        {
                            // If last activity extends over to next day, set end time to midnight.
                            duration = endDate - currentDate;
                            break;
                        }
                        else
                        {
                            duration = item.Timestamp - currentDate;
                        }
                        activitySummary[currentActivity] += duration;
                    }
                    currentActivity = item.Activity;
                    currentDate     = item.Timestamp.DateTime;
                }
            }

            // Prepare the summary to add it to data source
            List <ActivityDuration <Windows.Devices.Sensors.ActivityType> > historyList = new List <ActivityDuration <Windows.Devices.Sensors.ActivityType> >();

            foreach (var activityType in activityTypes)
            {
                // For each entry in the summary add the type and duration to data source
                historyList.Add(new ActivityDuration <Windows.Devices.Sensors.ActivityType>((Windows.Devices.Sensors.ActivityType)activityType, activitySummary[(Windows.Devices.Sensors.ActivityType)activityType]));
            }

            // Update the singleton instance of the data source
            ActivityData <Windows.Devices.Sensors.ActivityType> .Instance().History = historyList;

            ActivityData <Windows.Devices.Sensors.ActivityType> .Instance().Date = startDate;
        }
        /// <summary>
        /// This is the event handler for AccessChanged events.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void AccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs e)
        {
            var status = e.Status;
            if (status != DeviceAccessStatus.Allowed)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    rootPage.NotifyUser("Access denied to activity sensors", NotifyType.ErrorMessage);
                    _activitySensor = null;

                    ScenarioEnableReadingChangedButton.IsEnabled = true;
                    ScenarioDisableReadingChangedButton.IsEnabled = false;
                });
            }
        }
        /// <summary>
        /// This is the click handler for the 'Reading Changed On' button.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void ScenarioEnableReadingChanged(object sender, RoutedEventArgs e)
        {
            // Determine if we can access activity sensors
            if (_deviceAccessInformation.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.InVehicle);
                    _activitySensor.SubscribedActivities.Add(ActivityType.Biking);
                    _activitySensor.SubscribedActivities.Add(ActivityType.Fidgeting);

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

                    ScenarioEnableReadingChangedButton.IsEnabled = false;
                    ScenarioDisableReadingChangedButton.IsEnabled = true;
                    rootPage.NotifyUser("Subscribed to reading changes", NotifyType.StatusMessage);
                }
                else
                {
                    rootPage.NotifyUser("No activity sensor found", NotifyType.ErrorMessage);
                }
            }
            else
            {
                rootPage.NotifyUser("Access denied to activity sensors", NotifyType.ErrorMessage);
            }
        }
 public ActivitySensorEvents(ActivitySensor This)
 {
     this.This = This;
 }
Ejemplo n.º 33
0
 public SensorTests()
 {
     tSensor = new TemperatureSensor();
     pSensor = new PulseSensor();
     aSensor = new ActivitySensor();
 }