/// <summary>
        /// Listen for any changed in device access permission. The user can block access to the device while the device is in use.
        /// If the user blocks access to the device while the device is opened, the device's handle will be closed automatically by
        /// the system; it is still a good idea to close the device explicitly so that resources are cleaned up.
        ///
        /// Note that by the time the AccessChanged event is raised, the device handle may already be closed by the system.
        /// </summary>
        private void RegisterForDeviceAccessStatusChange()
        {
            deviceAccessInformation = DeviceAccessInformation.CreateFromId(deviceInformation.Id);

            deviceAccessEventHandler = new TypedEventHandler <DeviceAccessInformation, DeviceAccessChangedEventArgs>(this.OnDeviceAccessChanged);
            deviceAccessInformation.AccessChanged += deviceAccessEventHandler;
        }
Example #2
0
        public async void OnAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs args)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                var status = args.Status;

                string eventDescription = GetTimeStampedMessage("Device Access Status");

                eventDescription += " (" + status.ToString() + ")";

                AddEventDescription(eventDescription);

                if (DeviceAccessStatus.DeniedByUser == args.Status)
                {
                    rootPage.NotifyUser("Location has been disabled by the user. Enable access through the settings charm.", NotifyType.StatusMessage);
                }
                else if (DeviceAccessStatus.DeniedBySystem == args.Status)
                {
                    rootPage.NotifyUser("Location has been disabled by the system. The administrator of the device must enable location access through the location control panel.", NotifyType.StatusMessage);
                }
                else if (DeviceAccessStatus.Unspecified == args.Status)
                {
                    rootPage.NotifyUser("Location has been disabled by unspecified source. The administrator of the device may need to enable location access through the location control panel, then enable access through the settings charm.", NotifyType.StatusMessage);
                }
                else if (DeviceAccessStatus.Allowed == args.Status)
                {
                    // clear status
                    rootPage.NotifyUser("", NotifyType.StatusMessage);
                }
                else
                {
                    rootPage.NotifyUser("Unknown device access information status", NotifyType.StatusMessage);
                }
            });
        }
Example #3
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";
            }
        }
Example #4
0
        public async Task <bool> CheckDeviceAccessAsync()
        {
            var access = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.Location);

            if (access.CurrentStatus == DeviceAccessStatus.Unspecified)
            {
                var accessStatus = await Geolocator.RequestAccessAsync();

                if (accessStatus == GeolocationAccessStatus.Allowed)
                {
                    return(true);
                }

                return(false);
            }
            else if (access.CurrentStatus != DeviceAccessStatus.Allowed)
            {
                var message = Strings.Resources.PermissionNoLocationPosition;

                var confirm = await MessagePopup.ShowAsync(message, Strings.Resources.AppName, Strings.Resources.PermissionOpenSettings, Strings.Resources.OK);

                if (confirm == ContentDialogResult.Primary)
                {
                    await Launcher.LaunchUriAsync(new Uri("ms-settings:privacy-location"));
                }

                return(false);
            }

            return(true);
        }
        private async Task Connect(DeviceInformation deviceInformation)
        {
            // Perform device access checks before trying to get the device.
            // First, we check if consent has been explicitly denied by the user.
            var accessStatus = DeviceAccessInformation.CreateFromId(deviceInformation.Id).CurrentStatus;

            if (accessStatus == DeviceAccessStatus.DeniedByUser)
            {
                throw new UnauthorizedAccessException("This app does not have access to connect to the remote device (please grant access in Settings > Privacy > Other Devices");
            }
            var bluetoothDevice = await BluetoothDevice.FromIdAsync(deviceInformation.Id);

            // This should return a list of uncached Bluetooth services (so if the server was not active when paired, it will still be detected by this call)
            var rfcommServices = await bluetoothDevice.GetRfcommServicesAsync();

            RfcommDeviceService bluetoothService = null;

            foreach (var service in rfcommServices.Services)
            {
                System.Diagnostics.Debug.WriteLine("Service {0}: {1}", service.ConnectionHostName, service.ConnectionServiceName);
                if (service.ServiceId.Uuid == RfcommServiceId.SerialPort.Uuid)
                {
                    bluetoothService = service;
                    break;
                }
            }
            if (bluetoothService != null)
            {
                bluetoothDevice.ConnectionStatusChanged += BluetoothDevice_ConnectionStatusChanged;
                var device = new UwpRfcommDevice(deviceInformation, bluetoothService);
                connectedDevices.Add(device.deviceInfo.Id, device);
                DeviceConnected?.Invoke(device);
            }
        }
Example #6
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);
            }
        }
        /// <summary>
        /// Close the device, Stop the Device Watcher, Stops listening for app events,
        /// reset object state to before a device was ever connected.
        /// </summary>
        public void CloseDevice()
        {
            if (IsDeviceConnected)
            {
                CloseCurrentlyConnectedDevice();
            }



            if (watcherStarted)
            {
                StopDeviceWatcher();
            }



            if (deviceAccessInformation != null)
            {
                UnregisterFromDeviceAccessStatusChange();
                deviceAccessInformation = null;
            }

            if (appSuspendEventHandler != null || appResumeEventHandler != null)
            {
                UnregisterFromAppEvents();
            }
            deviceInformation = null;

            bluetoothDevice = null;
            _socket.Dispose();
            _socket = null;
            deviceConnectedCallback = null;
            deviceCloseCallback     = null;
        }
Example #8
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);
            }
        }
Example #9
0
        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));
        }
Example #10
0
 /// <summary>
 /// Error handling for device level error conditions
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="args"></param>
 public async void OnAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs args)
 {
     await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
     {
         if (DeviceAccessStatus.DeniedByUser == args.Status)
         {
             Debug.WriteLine("Location has been disabled by the user. Enable access through the settings charm.");
         }
         else if (DeviceAccessStatus.DeniedBySystem == args.Status)
         {
             Debug.WriteLine("Location has been disabled by the system. The administrator of the device must enable location access through the location control panel.");
         }
         else if (DeviceAccessStatus.Unspecified == args.Status)
         {
             Debug.WriteLine("Location has been disabled by unspecified source. The administrator of the device may need to enable location access through the location control panel, then enable access through the settings charm.");
         }
         else if (DeviceAccessStatus.Allowed == args.Status)
         {
         }
         else
         {
             Debug.WriteLine("Unknown device access information status");
         }
     });
 }
Example #11
0
 private async void AccessInformationOnAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs args)
 {
     if (args.Status == DeviceAccessStatus.DeniedByUser)
     {
         await TryGetPermissionsAsync().ConfigureAwait(false);
     }
 }
Example #12
0
        private static async Task <bool> Initialize()
        {
            bool initializedSuccessfully = false;

            accessInfo = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.Location);
            try
            {
                if (geolocator == null)
                {
                    geolocator = new Geolocator();
                }

                // Get cancellation token
                cts = new CancellationTokenSource();
                CancellationToken token = cts.Token;

                currentLocation = await geolocator.GetGeopositionAsync().AsTask(token);

                // other initialization for your app could go here

                accessInfo.AccessChanged += OnAccessChanged;
                GeofenceMonitor.Current.GeofenceStateChanged += OnGeofenceStateChanged;
                initializedSuccessfully = true;
            }
            catch (UnauthorizedAccessException)
            {
                if (DeviceAccessStatus.DeniedByUser == accessInfo.CurrentStatus)
                {
                    MessageBox.Show("Location has been disabled by the user. Enable access through the settings charm.");
                }
                else if (DeviceAccessStatus.DeniedBySystem == accessInfo.CurrentStatus)
                {
                    MessageBox.Show("Location has been disabled by the system. The administrator of the device must enable location access through the location control panel.");
                }
                else if (DeviceAccessStatus.Unspecified == accessInfo.CurrentStatus)
                {
                    MessageBox.Show("Location has been disabled by unspecified source. The administrator of the device may need to enable location access through the location control panel, then enable access through the settings charm.");
                }
            }
            catch (TaskCanceledException)
            {
                // task cancelled
            }
            catch (Exception)
            {
                if (geolocator.LocationStatus == PositionStatus.Disabled)
                {
                    // On Windows Phone, this exception will be thrown when you call
                    // GetGeopositionAsync if the user has disabled locaton in Settings.
                    MessageBox.Show("Location has been disabled in Settings.");
                }
            }
            finally
            {
                cts = null;
            }

            return(initializedSuccessfully);
        }
        private static async Task<bool> Initialize()
        {
            bool initializedSuccessfully = false;

            accessInfo = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.Location);
            try
            {
                if (geolocator == null)
                {
                    geolocator = new Geolocator();
                }

                // Get cancellation token
                cts = new CancellationTokenSource();
                CancellationToken token = cts.Token;

                currentLocation = await geolocator.GetGeopositionAsync().AsTask(token);

                // other initialization for your app could go here

                accessInfo.AccessChanged += OnAccessChanged;
                GeofenceMonitor.Current.GeofenceStateChanged += OnGeofenceStateChanged;
                initializedSuccessfully = true;
            }
            catch (UnauthorizedAccessException)
            {
                if (DeviceAccessStatus.DeniedByUser == accessInfo.CurrentStatus)
                {
                    MessageBox.Show("Location has been disabled by the user. Enable access through the settings charm.");
                }
                else if (DeviceAccessStatus.DeniedBySystem == accessInfo.CurrentStatus)
                {
                    MessageBox.Show("Location has been disabled by the system. The administrator of the device must enable location access through the location control panel.");
                }
                else if (DeviceAccessStatus.Unspecified == accessInfo.CurrentStatus)
                {
                    MessageBox.Show("Location has been disabled by unspecified source. The administrator of the device may need to enable location access through the location control panel, then enable access through the settings charm.");
                }
            }
            catch (TaskCanceledException)
            {
                // task cancelled
            }
            catch (Exception)
            {
                if (geolocator.LocationStatus == PositionStatus.Disabled)
                {
                    // On Windows Phone, this exception will be thrown when you call 
                    // GetGeopositionAsync if the user has disabled locaton in Settings.
                    MessageBox.Show("Location has been disabled in Settings.");
                }
            }
            finally
            {
                cts = null;
            }

            return initializedSuccessfully;
        }
        /// <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);
        }
Example #16
0
        /// <summary>
        /// This method opens the device using the WinRT USB API. After the device is opened, save the device
        /// so that it can be used across scenarios.
        ///
        /// It is important that the FromIdAsync call is made on the UI thread because the consent prompt can only be displayed
        /// on the UI thread.
        ///
        /// This method is used to reopen the device after the device reconnects to the computer and when the app resumes.
        /// </summary>
        /// <param name="deviceInfo">Device information of the device to be opened</param>
        /// <param name="deviceSelector">The AQS used to find this device</param>
        /// <returns>True if the device was successfully opened, false if the device could not be opened for well known reasons.
        /// An exception may be thrown if the device could not be opened for extraordinary reasons.</returns>
        public async Task <bool> OpenDeviceAsync(DeviceInformation deviceInfo, String deviceSelector)
        {
            Device = await UsbDevice.FromIdAsync(deviceInfo.Id);

            Boolean successfullyOpenedDevice = false;

            MainPage.NotifyType notificationStatus;
            String notificationMessage = null;

            // Device could have been blocked by user or the device has already been opened by another app.
            if (Device != null)
            {
                successfullyOpenedDevice = true;

                DeviceInformation   = deviceInfo;
                this.DeviceSelector = deviceSelector;

                notificationStatus  = MainPage.NotifyType.StatusMessage;
                notificationMessage = "Device Opened";

                // Notify registered callback handle that the device has been opened
                if (OnDeviceConnected != null)
                {
                    OnDeviceConnected(this, DeviceInformation);
                }
            }
            else
            {
                successfullyOpenedDevice = false;

                notificationStatus = MainPage.NotifyType.ErrorMessage;

                DeviceAccessInformation dai = DeviceAccessInformation.CreateFromId(deviceInfo.Id);

                var deviceAccessStatus = dai.CurrentStatus;

                if (deviceAccessStatus == DeviceAccessStatus.DeniedByUser)
                {
                    notificationMessage = "Access to the device was blocked by the user.";
                }
                else if (deviceAccessStatus == DeviceAccessStatus.DeniedBySystem)
                {
                    // This status is most likely caused by app permissions (did not declare the device in the app's package.appxmanifest)
                    // This status does not cover the case where the device is already opened by another app.
                    notificationMessage = "Access to the device was blocked by the system.";
                }
                else
                {
                    // The only time I made it to this error I forgot to add Fadecandy to package.appxmanifest
                    // Most likely the device is opened by another app, but cannot be sure
                    notificationMessage = "Unknown error, possibly opened by another app.";
                }
            }

            MainPage.Current.NotifyUser(notificationMessage, deviceInfo.Id, notificationStatus);

            return(successfullyOpenedDevice);
        }
        private void RegisterForDeviceAccessStatusChange()
        {
            if (_deviceAccessInformation == null)
            {
                _deviceAccessInformation = DeviceAccessInformation.CreateFromId(DeviceInformation.Id);
            }

            _deviceAccessInformation.AccessChanged += OnAccessInformation_AccessChanged;
        }
Example #18
0
        public MainPage()
        {
            this.InitializeComponent();

            m_deviceAccessInformation = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.AudioCapture);
            // Note: In unpatched RS4 the OnAccessChanged method will never be called.
            // This is fixed in RS5 and an upcoming update to RS4
            m_deviceAccessInformation.AccessChanged += new TypedEventHandler <DeviceAccessInformation, DeviceAccessChangedEventArgs>(OnAccessChanged);
        }
        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);
        }
        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);
        }
        private void RegisterForDeviceAccessStatusChange()
        {
            // Enable the following registration ONLY if the Serial device under test is non-internal.
            //

            deviceAccessInformation  = DeviceAccessInformation.CreateFromId(deviceId);
            deviceAccessEventHandler = new TypedEventHandler <DeviceAccessInformation, DeviceAccessChangedEventArgs>(this.OnDeviceAccessChanged);
            deviceAccessInformation.AccessChanged += deviceAccessEventHandler;
        }
        /// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            DeviceAccessInformation accessInfo;

            accessInfo = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.Location);
            accessInfo.AccessChanged += OnAccessChanged;
            Initialize();
            CreateGeofence();
        }
Example #23
0
        private async Task <bool> CheckDeviceAccessAsync(bool audio, ChatRecordMode mode)
        {
            // For some reason, as far as I understood, CurrentStatus is always Unspecified on Xbox
            if (string.Equals(AnalyticsInfo.VersionInfo.DeviceFamily, "Windows.Xbox"))
            {
                return(true);
            }

            var access = DeviceAccessInformation.CreateFromDeviceClass(audio ? DeviceClass.AudioCapture : DeviceClass.VideoCapture);

            if (access.CurrentStatus == DeviceAccessStatus.Unspecified)
            {
                MediaCapture capture = null;
                try
                {
                    capture = new MediaCapture();
                    var settings = new MediaCaptureInitializationSettings();
                    settings.StreamingCaptureMode = mode == ChatRecordMode.Video
                        ? StreamingCaptureMode.AudioAndVideo
                        : StreamingCaptureMode.Audio;
                    await capture.InitializeAsync(settings);
                }
                catch { }
                finally
                {
                    if (capture != null)
                    {
                        capture.Dispose();
                        capture = null;
                    }
                }

                return(false);
            }
            else if (access.CurrentStatus != DeviceAccessStatus.Allowed)
            {
                var message = audio
                    ? mode == ChatRecordMode.Voice
                    ? Strings.Resources.PermissionNoAudio
                    : Strings.Resources.PermissionNoAudioVideo
                    : Strings.Resources.PermissionNoCamera;

                this.BeginOnUIThread(async() =>
                {
                    var confirm = await MessagePopup.ShowAsync(message, Strings.Resources.AppName, Strings.Resources.PermissionOpenSettings, Strings.Resources.OK);
                    if (confirm == ContentDialogResult.Primary)
                    {
                        await Launcher.LaunchUriAsync(new Uri("ms-settings:appsfeatures-app"));
                    }
                });

                return(false);
            }

            return(true);
        }
Example #24
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>
 /// Close the device if the device access was denied by anyone (system or the user) and reopen it if permissions are allowed again
 /// </summary>
 private async void OnDeviceAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs eventArgs)
 {
     if ((eventArgs.Status == DeviceAccessStatus.DeniedBySystem) || (eventArgs.Status == DeviceAccessStatus.DeniedByUser))
     {
         CloseCurrentlyConnectedDevice();
     }
     else if ((eventArgs.Status == DeviceAccessStatus.Allowed) && (DeviceInformation != null) && IsEnabledAutoReconnect)
     {
         await OpenDeviceAsync(DeviceInformation);
     }
 }
 /// <summary>
 /// Close the device if the device access was denied by anyone (system or the user) and reopen it if permissions are allowed again
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="eventArgs"></param>
 private void OnDeviceAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs eventArgs)
 {
     if ((eventArgs.Status == DeviceAccessStatus.DeniedBySystem) ||
         (eventArgs.Status == DeviceAccessStatus.DeniedByUser))
     {
         CloseCurrentlyConnectedDevice();
     }
     else if ((eventArgs.Status == DeviceAccessStatus.Allowed) && (_deviceInformation != null))
     {
     }
 }
        /// <summary>
        /// Invoked when ActivitySensor device access gets changed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void DeviceAccessInfo_AccessChangedAsync(DeviceAccessInformation sender, DeviceAccessChangedEventArgs args)
        {
            var status = args.Status;

            if (status == DeviceAccessStatus.Allowed)
            {
                await InitializeAsync();
            }
            else
            {
                Release();
            }
        }
        /// <summary>
        /// Invoked when ActivitySensor device access gets changed.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="args"></param>
        private async void DeviceAccessInfo_AccessChangedAsync(DeviceAccessInformation sender, DeviceAccessChangedEventArgs args)
        {
            var status = args.Status;

            if (status == DeviceAccessStatus.Allowed)
            {
                await InitializeAsync();
            }
            else
            {
                Release();
            }
        }
        /// <summary>
        /// This is the event handler for AccessChanged events.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void OnAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs e)
        {
            var status = e.Status;

            if (status != DeviceAccessStatus.Allowed)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    rootPage.NotifyUser("Custom sensor access denied", NotifyType.ErrorMessage);
                    customSensor = null;
                });
            }
        }
Example #30
0
        private async Task XboxJoystickInit(DeviceInformationCollection deviceInformationCollection)
        {
            //string deviceSelector = HidDevice.GetDeviceSelector(0x01, 0x05);
            //DeviceInformationCollection deviceInformationCollection = await DeviceInformation.FindAllAsync(deviceSelector);

            DeviceId = null;
            int deviceCount = deviceInformationCollection.Count;

            if (deviceCount == 0)
            {
                Debug.WriteLine("Error: No Xbox360 controller found!");
                JoystickIsWorking = false;
            }
            else
            {
                foreach (DeviceInformation d in deviceInformationCollection)
                {
                    Debug.WriteLine("OK: Found: Xbox 360 Joystick Device ID: " + d.Id);

                    HidDevice hidDevice = await HidDevice.FromIdAsync(d.Id, Windows.Storage.FileAccessMode.Read);

                    if (hidDevice == null)
                    {
                        JoystickIsWorking = false;
                        try
                        {
                            var deviceAccessStatus = DeviceAccessInformation.CreateFromId(d.Id).CurrentStatus;

                            if (!deviceAccessStatus.Equals(DeviceAccessStatus.Allowed))
                            {
                                Debug.WriteLine("IP: DeviceAccess: " + deviceAccessStatus.ToString());
                            }
                        }
                        catch (Exception e)
                        {
                            Debug.WriteLine("Error: Xbox init - " + e.Message);
                        }

                        Debug.WriteLine("Error: Failed to connect to Xbox 360 Joystick controller!");
                    }
                    else
                    {
                        controller = new XboxHidController(hidDevice);
                        controller.JoystickDataChanged += Controller_JoystickDataChanged;
                        JoystickIsWorking = true;
                        DeviceId          = d.Id;
                    }
                }
            }
            lastControllerCount = deviceCount;
        }
Example #31
0
        private async Task <SerialDevice> GetSerialDeviceAsync(string serialPortName)
        {
            Assure.CheckFlowState(!string.IsNullOrEmpty(serialPortName), $"Empty '{nameof(serialPortName)}'.");

            // ReSharper disable AssignNullToNotNullAttribute
            var aqsFilter = SerialDevice.GetDeviceSelector(serialPortName);
            // ReSharper restore AssignNullToNotNullAttribute
            var deviceInformation = (await DeviceInformation.FindAllAsync(aqsFilter)).FirstOrDefault();

            if (deviceInformation == null)
            {
                throw new DeviceIoPortInitializationException($"Serial device on '{serialPortName}' port was not found.");
            }

            var portOpenningTry = 0;

GetSerialDeviceTry:
            portOpenningTry++;

            var serialDevice = await SerialDevice.FromIdAsync(deviceInformation.Id);

            if (serialDevice != null)
            {
                return(serialDevice);
            }

            var deviceAccessStatus = DeviceAccessInformation.CreateFromId(deviceInformation.Id).CurrentStatus;

            switch (deviceAccessStatus)
            {
            case DeviceAccessStatus.DeniedByUser:
                throw new DeviceIoPortInitializationException($"Access to device on '{serialPortName}' port was blocked by the user.");

            case DeviceAccessStatus.DeniedBySystem:
                // This status is most likely caused by app permissions (did not declare the device in the app's package.appxmanifest)
                // This status does not cover the case where the device is already opened by another app.
                throw new DeviceIoPortInitializationException($"Access to device on '{serialPortName}' was blocked by the system.");

            default:
                // Sometimes serial port is not freed fast after previous Dispose. Retry.
                var message = $"Access to device on '{serialPortName}' was blocked with unknown error (try {portOpenningTry}). Possibly opened by another app.";
                if (portOpenningTry < MaxPortOpenningTries)
                {
                    Log.Error(LogContextEnum.Device, message);
                    await Task.Delay(PortOpenningTryDelay);

                    goto GetSerialDeviceTry;
                }
                throw new DeviceIoPortInitializationException(message);
            }
        }
Example #32
0
 private static void OnAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs args)
 {
     if (Dispatcher != null)
     {
         Dispatcher.BeginInvoke(() =>
         {
             OnAccessChanged(args);
         });
     }
     else
     {
         OnAccessChanged(args);
     }
 }
Example #33
0
        private async Task <bool> CheckDeviceAccessAsync()
        {
            var access = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.AudioCapture);

            if (access.CurrentStatus == DeviceAccessStatus.Unspecified)
            {
                MediaCapture capture = null;
                try
                {
                    capture = new MediaCapture();
                    var settings = new MediaCaptureInitializationSettings
                    {
                        StreamingCaptureMode = StreamingCaptureMode.Audio
                    };
                    await capture.InitializeAsync(settings);
                }
                catch { }
                finally
                {
                    if (capture != null)
                    {
                        capture.Dispose();
                        capture = null;
                    }
                }

                return(false);
            }
            else if (access.CurrentStatus != DeviceAccessStatus.Allowed)
            {
                //var message = audio
                //    ? mode == ChatRecordMode.Voice
                //    ? Strings.Resources.PermissionNoAudio
                //    : Strings.Resources.PermissionNoAudioVideo
                //    : Strings.Resources.PermissionNoCamera;

                //this.BeginOnUIThread(async () =>
                //{
                //    var confirm = await TLMessageDialog.ShowAsync(message, Strings.Resources.AppName, Strings.Resources.PermissionOpenSettings, Strings.Resources.OK);
                //    if (confirm == ContentDialogResult.Primary)
                //    {
                //        await Launcher.LaunchUriAsync(new Uri("ms-settings:appsfeatures-app"));
                //    }
                //});

                return(false);
            }

            return(true);
        }
        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);
        }
        /// <summary>
        /// Close the device if the device access was denied by anyone (system or the user) and reopen it if permissions are allowed again
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="eventArgs"></param>
        private async void OnDeviceAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs eventArgs)
        {
            if ((eventArgs.Status == DeviceAccessStatus.DeniedBySystem)
                || (eventArgs.Status == DeviceAccessStatus.DeniedByUser))
            {
                CloseCurrentlyConnectedDevice();
            }
            else if ((eventArgs.Status == DeviceAccessStatus.Allowed) && (deviceInformation != null) && isEnabledAutoReconnect)
            {
                await rootPage.Dispatcher.RunAsync(
                    CoreDispatcherPriority.Normal,
                    new DispatchedHandler(async () =>
                    {
                        // If we failed to reconnect to the device, don't try to connect anymore
                        isEnabledAutoReconnect = await OpenDeviceAsync(deviceInformation, deviceSelector);

                        // Any app specific device intialization should be done here because we don't know the state of the device when it is re-enumerated.
                    }));
            }
        }
        /// <summary>
        /// Listen for any changed in device access permission. The user can block access to the device while the device is in use.
        /// If the user blocks access to the device while the device is opened, the device's handle will be closed automatically by
        /// the system; it is still a good idea to close the device explicitly so that resources are cleaned up.
        /// 
        /// Note that by the time the AccessChanged event is raised, the device handle may already be closed by the system.
        /// </summary>
        private void RegisterForDeviceAccessStatusChange()
        {
            deviceAccessInformation = DeviceAccessInformation.CreateFromId(deviceInformation.Id);

            deviceAccessEventHandler = new TypedEventHandler<DeviceAccessInformation, DeviceAccessChangedEventArgs>(this.OnDeviceAccessChanged);
            deviceAccessInformation.AccessChanged += deviceAccessEventHandler;
        }
        /// <summary>
        /// Closes the device, stops the device watcher, stops listening for app events, and resets object state to before a device
        /// was ever connected.
        /// </summary>
        public void CloseDevice()
        {
            if (IsDeviceConnected)
            {
                CloseCurrentlyConnectedDevice();
            }

            if (deviceWatcher != null)
            {
                if (watcherStarted)
                {
                    StopDeviceWatcher();

                    UnregisterFromDeviceWatcherEvents();
                }

                deviceWatcher = null;
            }

            if (deviceAccessInformation != null)
            {
                UnregisterFromDeviceAccessStatusChange();

                deviceAccessInformation = null;
            }

            if (appSuspendEventHandler != null || appResumeEventHandler != null)
            {
                UnregisterFromAppEvents();
            }

            deviceInformation = null;
            deviceSelector = null;

            deviceConnectedCallback= null;
            deviceCloseCallback = null;

            isEnabledAutoReconnect = true;
        }
        /// <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;
                });
            }
        }
 public DeviceAccessInformationEvents(DeviceAccessInformation This)
 {
     this.This = This;
 }
        /// <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 OnAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs e)
 {
     var status = e.Status;
     if (status != DeviceAccessStatus.Allowed)
     {
         await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
         {
             rootPage.NotifyUser("Custom sensor access denied", NotifyType.ErrorMessage);
             customSensor = null;
         });
     }
 }
 private static void OnAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs args)
 {
     if (Dispatcher != null)
     {
         Dispatcher.BeginInvoke(() =>
         {
             OnAccessChanged(args);
         });
     }
     else
     {
         OnAccessChanged(args);
     }
 }
        public async void OnAccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs args)
        {
            await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
            {
                var status = args.Status;

                string eventDescription = GetTimeStampedMessage("Device Access Status");
                
                eventDescription += " (" + status.ToString() + ")";

                AddEventDescription(eventDescription);

                if (DeviceAccessStatus.DeniedByUser == args.Status)
                {
                    rootPage.NotifyUser("Location has been disabled by the user. Enable access through the settings charm.", NotifyType.StatusMessage);
                }
                else if (DeviceAccessStatus.DeniedBySystem == args.Status)
                {
                    rootPage.NotifyUser("Location has been disabled by the system. The administrator of the device must enable location access through the location control panel.", NotifyType.StatusMessage);
                }
                else if (DeviceAccessStatus.Unspecified == args.Status)
                {
                    rootPage.NotifyUser("Location has been disabled by unspecified source. The administrator of the device may need to enable location access through the location control panel, then enable access through the settings charm.", NotifyType.StatusMessage);
                }
                else if (DeviceAccessStatus.Allowed == args.Status)
                {
                    // clear status
                    rootPage.NotifyUser("", NotifyType.StatusMessage);
                }
                else
                {
                    rootPage.NotifyUser("Unknown device access information status", NotifyType.StatusMessage);
                }
            });
        }
        /// <summary>
        /// This is the event handler for AccessChanged events.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        async private void AccessChanged(DeviceAccessInformation sender, DeviceAccessChangedEventArgs e)
        {
            var status = e.Status;
            if (status != DeviceAccessStatus.Allowed)
            {
                await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                {
                    rootPage.NotifyUser("Access denied to pedometers", NotifyType.ErrorMessage);
                    pedometer = null;

                    registeredForEvents = false;
                    RegisterButton.Content = "Register ReadingChanged";
                });
            }
        }
        public Scenario4()
        {
            this.InitializeComponent();

            try
            {
                formatterShortDateLongTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("{month.integer}/{day.integer}/{year.full} {hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                formatterLongTime = new Windows.Globalization.DateTimeFormatting.DateTimeFormatter("{hour.integer}:{minute.integer(2)}:{second.integer(2)}", new[] { "en-US" }, "US", Windows.Globalization.CalendarIdentifiers.Gregorian, Windows.Globalization.ClockIdentifiers.TwentyFourHour);
                calendar = new Windows.Globalization.Calendar();
                decimalFormatter = new Windows.Globalization.NumberFormatting.DecimalFormatter();

                geofenceCollection = new GeofenceItemCollection();
                eventCollection = new EventDescriptorCollection();

                // Get a geolocator object
                geolocator = new Geolocator();

                geofences = GeofenceMonitor.Current.Geofences;

                // using data binding to the root page collection of GeofenceItems
                RegisteredGeofenceListBox.DataContext = geofenceCollection;

                // using data binding to the root page collection of GeofenceItems associated with events
                GeofenceEventsListBox.DataContext = eventCollection;

                FillRegisteredGeofenceListBoxWithExistingGeofences();
                FillEventListBoxWithExistingEvents();

#if WINDOWS_APP
                accessInfo = DeviceAccessInformation.CreateFromDeviceClass(DeviceClass.Location);
                accessInfo.AccessChanged += OnAccessChanged;
#endif

                coreWindow = CoreWindow.GetForCurrentThread(); // this needs to be set before InitializeComponent sets up event registration for app visibility
                coreWindow.VisibilityChanged += OnVisibilityChanged;

                // register for state change events
                GeofenceMonitor.Current.GeofenceStateChanged += OnGeofenceStateChanged;
                GeofenceMonitor.Current.StatusChanged += OnGeofenceStatusChanged;
            }
#if WINDOWS_APP
            catch (UnauthorizedAccessException)
            {
                if (DeviceAccessStatus.DeniedByUser == accessInfo.CurrentStatus)
                {
                    rootPage.NotifyUser("Location has been disabled by the user. Enable access through the settings charm.", NotifyType.StatusMessage);
                }
                else if (DeviceAccessStatus.DeniedBySystem == accessInfo.CurrentStatus)
                {
                    rootPage.NotifyUser("Location has been disabled by the system. The administrator of the device must enable location access through the location control panel.", NotifyType.StatusMessage);
                }
                else if (DeviceAccessStatus.Unspecified == accessInfo.CurrentStatus)
                {
                    rootPage.NotifyUser("Location has been disabled by unspecified source. The administrator of the device may need to enable location access through the location control panel, then enable access through the settings charm.", NotifyType.StatusMessage);
                }
            }
#endif
            catch (Exception ex)
            {
                // GeofenceMonitor failed in adding a geofence
                // exceptions could be from out of memory, lat/long out of range,
                // too long a name, not a unique name, specifying an activation
                // time + duration that is still in the past

                // If ex.HResult is RPC_E_DISCONNECTED (0x80010108):
                // The Location Framework service event state is out of synchronization
                // with the Windows.Devices.Geolocation.Geofencing.GeofenceMonitor.
                // To recover remove all event handlers on the GeofenceMonitor or restart the application.
                // Once all event handlers are removed you may add back any event handlers and retry the operation.

                rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
            }
        }