Пример #1
0
        /// <summary>
        /// Called to pair a targeted device
        /// </summary>
        /// <param name="pairButton">Pair button</param>
        /// <param name="currentDevice">Displayable information for the targeted device</param>
        public async Task PairingRequestedAsync(Button pairButton, BluetoothDeviceInfo currentDevice)
        {
            try
            {
                _deviceInfo           = currentDevice;
                _inProgressPairButton = pairButton;

                // Display confirmation message panel
                string deviceIdentifier    = _deviceInfo.Name != BluetoothDeviceNameUnknownText ? _deviceInfo.Name : _deviceInfo.IdWithoutProtocolPrefix;
                string confirmationMessage = string.Format(BluetoothAttemptingToPairFormat, _deviceInfo.Name, _deviceInfo.IdWithoutProtocolPrefix);

                await DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage);

                // Save the flyout and set to null so it doesn't appear without explicitly being called
                _savedPairButtonFlyout       = pairButton.Flyout;
                _inProgressPairButton.Flyout = null;
                pairButton.IsEnabled         = false;

                // Specify custom pairing with all ceremony types and protection level EncryptionAndAuthentication
                DevicePairingKinds           ceremoniesSelected = GetSelectedCeremonies();
                DevicePairingProtectionLevel protectionLevel    = DevicePairingProtectionLevel.Default;

                // Setup a custom pairing and handler, then get the results of the request
                DeviceInformationCustomPairing customPairing = _deviceInfo.DeviceInformation.Pairing.Custom;
                customPairing.PairingRequested += PairingRequestedHandlerAsync;
                DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

                if (result.Status == DevicePairingResultStatus.Paired)
                {
                    confirmationMessage = string.Format(BluetoothPairingSuccessFormat, deviceIdentifier, result.Status.ToString());
                }
                else
                {
                    confirmationMessage = string.Format(BluetoothPairingFailureFormat, deviceIdentifier, result.Status.ToString());
                }

                // Display the result of the pairing attempt
                await DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage);

                // If the watcher toggle is on, clear any devices in the list and stop and restart the watcher to ensure their current state is reflected
                if (BluetoothWatcherEnabled)
                {
                    BluetoothDeviceCollection.Clear();
                    StopWatcher();
                    StartWatcherAsync();
                }
                else
                {
                    // If the watcher is off, this is an inbound request so we only need to clear the list
                    BluetoothDeviceCollection.Clear();
                }

                _inProgressPairButton = null;
                pairButton.IsEnabled  = true;
            }
            catch (Exception ex)
            {
                LogService.Write(ex.ToString(), LoggingLevel.Error);
            }
        }
        private async void PairButton_Click(object sender, RoutedEventArgs e)
        {
            // Gray out the pair button and results view while pairing is in progress.
            resultsListView.IsEnabled = false;
            pairButton.IsEnabled      = false;
            rootPage.NotifyUser("Pairing started. Please wait...", NotifyType.StatusMessage);

            // Get the device selected for pairing
            DeviceInformationDisplay deviceInfoDisp = resultsListView.SelectedItem as DeviceInformationDisplay;

            // Get ceremony type and protection level selections
            DevicePairingKinds           ceremoniesSelected  = GetSelectedCeremonies();
            ProtectionLevelSelectorInfo  protectionLevelInfo = (ProtectionLevelSelectorInfo)protectionLevelComboBox.SelectedItem;
            DevicePairingProtectionLevel protectionLevel     = protectionLevelInfo.ProtectionLevel;

            DeviceInformationCustomPairing customPairing = deviceInfoDisp.DeviceInformation.Pairing.Custom;

            customPairing.PairingRequested += PairingRequestedHandler;
            DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

            customPairing.PairingRequested -= PairingRequestedHandler;

            rootPage.NotifyUser(
                "Pairing result = " + result.Status.ToString(),
                result.Status == DevicePairingResultStatus.Paired ? NotifyType.StatusMessage : NotifyType.ErrorMessage);

            HidePairingPanel();
            UpdatePairingButtons();
            resultsListView.IsEnabled = true;
        }
Пример #3
0
        private async void DeviceDiscovered(BluetoothLEAdvertisementWatcher sender, BluetoothLEAdvertisementReceivedEventArgs advertisement)
        {
            var isNew = false;

            lock (this)
            {
                if (false == advertisedDevices.Contains(advertisement.BluetoothAddress))
                {
                    this.advertisedDevices.Add(advertisement.BluetoothAddress);
                    isNew = true;
                }
            }

            if (true == isNew)
            {
                var device = await BluetoothLEDevice.FromBluetoothAddressAsync(advertisement.BluetoothAddress);

                DevicePairingKinds             ceremoniesSelected = DevicePairingKinds.ConfirmOnly;
                DevicePairingProtectionLevel   protectionLevel    = DevicePairingProtectionLevel.None;
                DeviceInformationCustomPairing customPairing      = device.DeviceInformation.Pairing.Custom;

                customPairing.PairingRequested += PairingRequestedHandler;
                DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

                customPairing.PairingRequested -= PairingRequestedHandler;

                if ((result.Status == DevicePairingResultStatus.AlreadyPaired) || (result.Status == DevicePairingResultStatus.Paired))
                {
                    sender.Stop();
                }
            }
        }
Пример #4
0
        private async Task <bool> TryToPairDevice(DeviceInformation deviceInfo)
        {
            bool paired = false;

            if (deviceInfo != null)
            {
                if (deviceInfo.Pairing.IsPaired != true)
                {
                    paired = false;

                    DevicePairingKinds           ceremoniesSelected = DevicePairingKinds.ConfirmOnly | DevicePairingKinds.DisplayPin | DevicePairingKinds.ProvidePin | DevicePairingKinds.ConfirmPinMatch;
                    DevicePairingProtectionLevel protectionLevel    = DevicePairingProtectionLevel.Default;

                    // Specify custom pairing with all ceremony types and protection level EncryptionAndAuthentication
                    DeviceInformationCustomPairing customPairing = deviceInfo.Pairing.Custom;

                    customPairing.PairingRequested += PairingRequestedHandler;
                    DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

                    customPairing.PairingRequested -= PairingRequestedHandler;

                    if (result.Status == DevicePairingResultStatus.Paired)
                    {
                        paired = true;
                    }
                    else
                    {
                        StatusText.Text = "Pairing Failed " + result.Status.ToString();
                        EnableRetry();
                    }
                }
                else
                {
                    paired = true;
                }

                if (paired)
                {
                    // device is paired, set up the sensor Tag
                    StatusText.Text = "Verbunden, pairing versuch...";

                    DeviceInfoConnected = deviceInfo;

                    //Start watcher for Bluetooth LE Services
                    StartBLEWatcher();
                }
                else
                {
                }
            }
            else
            {
            }        //Null device
            return(paired);
        }
Пример #5
0
        private async void TryPair(string val)
        {
            DeviceInformationDisplay _deviceInformationDisplayConnect = ResultCollection.Where(r => r.Id == val).FirstOrDefault();

            DevicePairingKinds ceremoniesSelected = DevicePairingKinds.ConfirmOnly;
            //  ProtectionLevelSelectorInfo protectionLevelInfo = (ProtectionLevelSelectorInfo)protectionLevelComboBox.SelectedItem;

            DevicePairingProtectionLevel protectionLevel = DevicePairingProtectionLevel.Default;

            DeviceInformationCustomPairing customPairing = _deviceInformationDisplayConnect.DeviceInformation.Pairing.Custom;


            customPairing.PairingRequested += PairingRequestedHandler;

            DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

            customPairing.PairingRequested -= PairingRequestedHandler;


            StopWatcher();

            var bleDevice = await BluetoothLEDevice.FromIdAsync(_deviceInformationDisplayConnect.Id);



            var accService = await GattDeviceService.FromIdAsync(_deviceInformationDisplayConnect.Id);

            //Get the accelerometer data characteristic
            var accData = accService.GetCharacteristics(new Guid("151c0000-4580-4111-9ca1-5056f3454fbc"))[0];

            //Subcribe value changed

            //accData.ValueChanged += AccData_ValueChanged;
            accData.ValueChanged += test;

            //Set configuration to notify
            await accData.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify);

            //Get the accelerometer configuration characteristic
            var accConfig = accService.GetCharacteristics(new Guid("151c0000-4580-4111-9ca1-5056f3454fbc"))[0];

            GattReadResult Resultat = await accConfig.ReadValueAsync();

            var Output = Resultat.Value.ToArray();

            Debug.WriteLine("Acc: " + Output.Count());
            Debug.WriteLine("Registre 0:" + Output[0].ToString());
            Debug.WriteLine("Registre 1:" + Output[1].ToString());

            Output[0] = 0x7F;

            await accConfig.WriteValueAsync(Output.AsBuffer());
        }
        private async void PairButton_Click(object sender, RoutedEventArgs e)
        {
            DeviceInformationDisplay deviceInfoDisp = resultsListView.SelectedItem as DeviceInformationDisplay;

            if (deviceInfoDisp != null)
            {
                PairButton.IsEnabled = false;
                bool paired = true;
                //if (deviceInfoDisp.IsPaired != true)
                //{
                paired = false;
                DevicePairingKinds           ceremoniesSelected = DevicePairingKinds.ConfirmOnly | DevicePairingKinds.DisplayPin | DevicePairingKinds.ProvidePin | DevicePairingKinds.ConfirmPinMatch;
                DevicePairingProtectionLevel protectionLevel    = DevicePairingProtectionLevel.Default;

                // Specify custom pairing with all ceremony types and protection level EncryptionAndAuthentication
                DeviceInformationCustomPairing customPairing = deviceInfoDisp.DeviceInformation.Pairing.Custom;

                customPairing.PairingRequested += PairingRequestedHandler;
                DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

                customPairing.PairingRequested -= PairingRequestedHandler;

                if (result.Status == DevicePairingResultStatus.Paired)
                {
                    paired = true;
                }
                else
                {
                    //UserOut.Text = "Pairing Failed " + result.Status.ToString();
                }
                //UpdatePairingButtons();
                //}

                if (paired)
                {
                    // device is paired, set up the sensor Tag
                    //UserOut.Text = "Setting up SensorTag";

                    //DeviceInfoConnected = deviceInfoDisp;

                    //Start watcher for Bluetooth LE Services
                    //StartBLEWatcher();
                }
                PairButton.IsEnabled = true;
            }
        }
Пример #7
0
        public bool DoInAppPairing(DevicePairingProtectionLevel minProtectionLevel, IDevicePairingSettings devicePairingSettings)
        {
            Debug.WriteLine("Trying in app pairing");

            // BT_Code: Pair the currently selected device.
            DevicePairingResult result = DeviceInfo.Pairing.PairAsync(minProtectionLevel, devicePairingSettings).GetAwaiter().GetResult();

            Debug.WriteLine($"Pairing result: {result.Status}");

            if (result.Status != DevicePairingResultStatus.Paired ||
                result.Status != DevicePairingResultStatus.AlreadyPaired)
            {
                Debug.WriteLine("Pairing error: " + result.Status.ToString());
                return(false);
            }
            return(true);
        }
Пример #8
0
        private async void ResultsListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            resultsListView.IsEnabled = false;


            string val = resultsListView.SelectedValue.ToString();

            deviceInfoDisp = ResultCollection.Where(r => r.Id == val).FirstOrDefault();

            this.NotifyUser("Unpairing started. Please wait...", NotifyType.StatusMessage);

            DevicePairingKinds ceremoniesSelected = DevicePairingKinds.ConfirmOnly;
            //  ProtectionLevelSelectorInfo protectionLevelInfo = (ProtectionLevelSelectorInfo)protectionLevelComboBox.SelectedItem;

            DevicePairingProtectionLevel protectionLevel = DevicePairingProtectionLevel.Default;

            DeviceInformationCustomPairing customPairing = deviceInfoDisp.DeviceInformation.Pairing.Custom;

            Debug.WriteLine("Is Paired -- " + deviceInfoDisp.IsPaired);
            customPairing.PairingRequested += PairingRequestedHandler;

            DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

            customPairing.PairingRequested -= PairingRequestedHandler;

            if (result.Status == DevicePairingResultStatus.Paired || result.Status == DevicePairingResultStatus.AlreadyPaired)
            {
                Debug.WriteLine("Paired..");
            }
            deviceInfoDisp = ResultCollection.Where(r => r.Id == val).FirstOrDefault();
            Debug.WriteLine("Is Paired -- " + deviceInfoDisp.IsPaired);
            //this.NotifyUser(
            //    "Unpairing result = " + result.Status.ToString(),
            //    result.Status == DeviceUnpairingResultStatus.Unpaired ? NotifyType.StatusMessage : NotifyType.ErrorMessage);

            UpdateButtons(deviceInfoDisp);
            resultsListView.IsEnabled = true;
        }
Пример #9
0
        /// <summary>
        /// User wants to use custom pairing with the selected ceremony types and Default protection level
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void PairButton_Click(object sender, RoutedEventArgs e)
        {
            // Use the pair button on the bluetoothDeviceListView.SelectedItem to get the data context
            BluetoothDeviceInformationDisplay deviceInfoDisp =
                ((Button)sender).DataContext as BluetoothDeviceInformationDisplay;
            string formatString        = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothAttemptingToPairFormat");
            string confirmationMessage = string.Format(formatString, deviceInfoDisp.Name, deviceInfoDisp.Id);

            DisplayMessagePanelAsync(confirmationMessage, MessageType.InformationalMessage);

            // Save the pair button
            Button pairButton = sender as Button;

            inProgressPairButton = pairButton;

            // Save the flyout and set to null so it doesn't pop up unless we want it
            savedPairButtonFlyout       = pairButton.Flyout;
            inProgressPairButton.Flyout = null;

            // Disable the pair button until we are done
            pairButton.IsEnabled = false;

            // Get ceremony type and protection level selections
            DevicePairingKinds ceremoniesSelected = GetSelectedCeremonies();
            // Get protection level
            DevicePairingProtectionLevel protectionLevel = DevicePairingProtectionLevel.Default;

            // Specify custom pairing with all ceremony types and protection level EncryptionAndAuthentication
            DeviceInformationCustomPairing customPairing = deviceInfoDisp.DeviceInformation.Pairing.Custom;

            customPairing.PairingRequested += PairingRequestedHandler;
            DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

            if (result.Status == DevicePairingResultStatus.Paired)
            {
                formatString        = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothPairingSuccessFormat");
                confirmationMessage = string.Format(formatString, deviceInfoDisp.Name, deviceInfoDisp.Id);
            }
            else
            {
                formatString        = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothPairingFailureFormat");
                confirmationMessage = string.Format(formatString, result.Status.ToString(), deviceInfoDisp.Name,
                                                    deviceInfoDisp.Id);
            }
            // Display the result of the pairing attempt
            DisplayMessagePanelAsync(confirmationMessage, MessageType.InformationalMessage);

            // If the watcher toggle is on, clear any devices in the list and stop and restart the watcher to ensure state is reflected in list
            if (BluetoothToggle.IsOn)
            {
                bluetoothDeviceObservableCollection.Clear();
                StopWatcher();
                StartWatcher();
            }
            else
            {
                // If the watcher is off this is an inbound request so just clear the list
                bluetoothDeviceObservableCollection.Clear();
            }

            // Re-enable the pair button
            inProgressPairButton = null;
            pairButton.IsEnabled = true;
        }
Пример #10
0
        /// <summary>
        /// Called when an inbound Bluetooth connection is requested
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="inboundArgs"></param>
        private async void App_InboundPairingRequestedAsync(object sender, InboundPairingEventArgs inboundArgs)
        {
            LogService.Write("Bluetooth inbound pairing requested", LoggingLevel.Information);
            BluetoothServerHelper.Instance.Disconnect();

            // Ignore the inbound if pairing is already in progress
            if (_inProgressPairButton == null && !_isPairing)
            {
                try
                {
                    _isPairing = true;

                    // Restore the ceremonies we registered with
                    LogService.Write("Restoring supported ceremonies...", LoggingLevel.Information);

                    Object supportedPairingKinds = LocalSettings.Values["supportedPairingKinds"];
                    int    iSelectedCeremonies   = (int)DevicePairingKinds.ConfirmOnly;

                    if (supportedPairingKinds != null)
                    {
                        iSelectedCeremonies = (int)supportedPairingKinds;
                    }

                    // Clear any previous devices
                    LogService.Write("Refreshing Bluetooth devices...", LoggingLevel.Information);
                    BluetoothDeviceCollection.Clear();

                    // Add the latest information to display
                    BluetoothDeviceInfo currentDevice = new BluetoothDeviceInfo(inboundArgs.DeviceInfo);
                    BluetoothDeviceCollection.Add(currentDevice);

                    // Display a message about the inbound request
                    string confirmationMessage = string.Format(BluetoothAttemptingToPairFormat, currentDevice.Name, currentDevice.Id);

                    // Get the ceremony type and protection level selections
                    DevicePairingKinds ceremoniesSelected = GetSelectedCeremonies();

                    // Get the protection level
                    DevicePairingProtectionLevel protectionLevel = currentDevice.DeviceInformation.Pairing.ProtectionLevel;

                    // Specify custom pairing with all ceremony types and protection level EncryptionAndAuthentication
                    DeviceInformationCustomPairing customPairing = currentDevice.DeviceInformation.Pairing.Custom;
                    customPairing.PairingRequested += PairingRequestedHandlerAsync;
                    DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

                    if (result.Status == DevicePairingResultStatus.Paired)
                    {
                        confirmationMessage = string.Format(BluetoothPairingSuccessFormat, currentDevice.Name, currentDevice.IdWithoutProtocolPrefix);
                    }
                    else
                    {
                        confirmationMessage = string.Format(BluetoothPairingFailureFormat, currentDevice.Name, currentDevice.IdWithoutProtocolPrefix);
                    }

                    // Display the result of the pairing attempt
                    await DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage);
                }
                catch (Exception ex)
                {
                    LogService.Write(ex.ToString(), LoggingLevel.Error);
                }

                _isPairing = false;
            }
            else
            {
                LogService.Write("Pairing already in progress", LoggingLevel.Information);
            }
        }
Пример #11
0
        // -->> Device Pairing/Unpairing <<--
        // Pair Button: Click Event
        //___________________________________
        private async void pairButton_Click(object sender, RoutedEventArgs e)
        {
            pairButton.IsEnabled      = false;
            devicesListView.IsEnabled = false;
            rootPage.ShowProgressRing(pairingProgressRing, true);
            pairingCommandBar.Background = (SolidColorBrush)Application.Current.Resources["CommandBarBackground"];
            DeviceInformationDisplay deviceInfoSelected = devicesListView.SelectedItem as DeviceInformationDisplay;

            if (deviceInfoSelected != null) // Checks a device has been selected
            {
                bool paired = true;

                if (deviceInfoSelected.IsPaired != true) // Is device unpaired?
                {                                        // Pair Selectede Device
                    paired = false;

                    // Selects all the available ceremonies for pairing
                    DevicePairingKinds ceremoniesSelected =
                        DevicePairingKinds.ConfirmOnly | DevicePairingKinds.DisplayPin |
                        DevicePairingKinds.ProvidePin | DevicePairingKinds.ConfirmPinMatch;
                    DevicePairingProtectionLevel protectionLevel = DevicePairingProtectionLevel.Default;

                    // Specify a custom pairing with all ceremony types and EncryptionAndAuthentication protection
                    DeviceInformationCustomPairing customPairing = deviceInfoSelected.DeviceInformation.Pairing.Custom;
                    customPairing.PairingRequested += PairingRequested_EventHandler;

                    // Requesting pairing ...
                    pairingStatusTextBlock.Text = $"Pairing to {deviceInfoSelected.Name}";

                    // -->> Pairing device
                    DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

                    customPairing.PairingRequested -= PairingRequested_EventHandler;

                    switch (result.Status)
                    {
                    case DevicePairingResultStatus.Paired:    // Pairing succeeded
                        paired = true;
                        break;

                    case DevicePairingResultStatus.AccessDenied:    // Permission denied
                        pairingStatusTextBlock.Text = "Operation cancelled by the user";
                        break;

                    default:    // Failed
                        pairingStatusTextBlock.Text  = $"Pairing to {deviceInfoSelected.Name} failed";
                        pairingCommandBar.Background = new SolidColorBrush(Colors.Tomato);
                        break;
                    }

                    if (paired)
                    {
                        // Device paired correctly
                        StopWatcher();
                        StartWatcher();
                        pairingStatusTextBlock.Text  = $"Successfully paired to {deviceInfoSelected.Name}.";
                        pairingCommandBar.Background = new SolidColorBrush(Colors.LightGreen);
                        pairButton.Icon = new SymbolIcon(Symbol.Clear);

                        // Saving the Device ID and Name for future use
                        rootPage.selectedDeviceId   = deviceInfoSelected.Id;
                        rootPage.selectedDeviceName = deviceInfoSelected.Name;
                    }
                }
                else if (deviceInfoSelected.IsPaired) // Else, device is already paired
                {                                     // Unpair device
                    pairingStatusTextBlock.Text = $"Unpairing {deviceInfoSelected.Name}";

                    // -->> Unpairing device
                    DeviceInformationPairing deviceUnpairing = deviceInfoSelected.DeviceInformation.Pairing;
                    DeviceUnpairingResult    result          = await deviceUnpairing.UnpairAsync();

                    switch (result.Status)
                    {
                    case DeviceUnpairingResultStatus.Unpaired:    // Succeeded
                        StopWatcher();
                        StartWatcher();
                        pairingStatusTextBlock.Text  = $"{deviceInfoSelected.Name} unpaired successfully";
                        pairingCommandBar.Background = new SolidColorBrush(Colors.LightGreen);
                        pairButton.Content           = "Pair/Unpair Device";
                        rootPage.selectedDeviceId    = null;
                        rootPage.selectedDeviceName  = null;
                        break;

                    case DeviceUnpairingResultStatus.AccessDenied:    // Permission denied
                        pairingStatusTextBlock.Text = "Operation cancelled by the user";
                        break;

                    default:    // Failed
                        pairingStatusTextBlock.Text  = "Unpairing failed!";
                        pairingCommandBar.Background = new SolidColorBrush(Colors.Tomato);
                        break;
                    }
                }
            }
            rootPage.ShowProgressRing(pairingProgressRing, false);
            pairButton.IsEnabled      = true;
            devicesListView.IsEnabled = true;
        }
Пример #12
0
        private async void CheckPairing(DeviceInformationDisplay deviceInfoDisplay)
        {
            Debug.WriteLine("{0}- '{1}' Signal Strength - {2}", DateTime.Now.Ticks, deviceInfoDisplay.Name, deviceInfoDisplay.SignalStrength);

            if (!deviceInfoDisplay.IsPairing)
            {
                // Pair device only if it is close
                if (deviceInfoDisplay.Name.StartsWith("XY") &&
                    !deviceInfoDisplay.IsPaired &&
                    (deviceInfoDisplay.SignalStrength > -50))
                {
                    // Set a flag on the device so that once it begins to pair, it doesn't constantly try to pair
                    deviceInfoDisplay.IsPairing = true;

                    // This is just basic pairing (No PIN or confirmation)
                    DevicePairingKinds             ceremonies      = DevicePairingKinds.ConfirmOnly;
                    DevicePairingProtectionLevel   protectionLevel = DevicePairingProtectionLevel.Default;
                    DeviceInformationCustomPairing customPairing   = deviceInfoDisplay.DeviceInformation.Pairing.Custom;

                    // In the cases where more complex pairing is required, user interaction happens in the Pairing Requested event
                    customPairing.PairingRequested += OnPairingRequested;
                    DevicePairingResult result = await customPairing.PairAsync(ceremonies, protectionLevel);

                    customPairing.PairingRequested -= OnPairingRequested;

                    Debug.WriteLine("{0} pair result - {1}", deviceInfoDisplay.Name, result.Status);

                    // If the pair was successful, act based on the beacon ID
                    if (DevicePairingResultStatus.Paired == result.Status)
                    {
                        var stream = await _speechSynth.SynthesizeTextToStreamAsync("Paired beacon ID " + deviceInfoDisplay.Name);

                        // Use a dispatcher to play the audio
                        var ignored = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                        {
                            //Set the souce of the MediaElement to the SpeechSynthesisStream
                            _audio.SetSource(stream, stream.ContentType);

                            //Play the stream
                            _audio.Play();
                        });
                    }

                    deviceInfoDisplay.IsPairing = false;
                }
                else if (deviceInfoDisplay.Name.StartsWith("XY") &&
                         deviceInfoDisplay.IsPaired &&
                         (deviceInfoDisplay.SignalStrength < -50))
                {
                    // Set a flag on the device so that once it begins to pair, it doesn't constantly try to unpair
                    deviceInfoDisplay.IsPairing = true;

                    // Unpair the beacon
                    DeviceUnpairingResult result = await deviceInfoDisplay.DeviceInformation.Pairing.UnpairAsync();

                    Debug.WriteLine("{0} unpair result - {1}", deviceInfoDisplay.Name, result.Status);

                    deviceInfoDisplay.IsPairing = false;
                }
            }
        }
Пример #13
0
        /// <summary>
        /// User wants to use custom pairing with the selected ceremony types and Default protection level
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void PairButton_Click(object sender, RoutedEventArgs e)
        {
            // Use the pair button on the bluetoothDeviceListView.SelectedItem to get the data context
            BluetoothDeviceInformationDisplay deviceInfoDisp = ((Button)sender).DataContext as BluetoothDeviceInformationDisplay;

            ResourceLoader loader = ResourceLoader.GetForCurrentView();

            string formatString        = loader.GetString("BluetoothAttemptingToPair/Text");
            string confirmationMessage = formatString + deviceInfoDisp.Name + " (" + deviceInfoDisp.Id + ")";

            ViewModel.DisplayMessagePanelAsync(confirmationMessage, SettingBluetoothViewModel.MessageType.InformationalMessage);

            // Save the pair button
            Button pairButton = sender as Button;

            ViewModel.InProgressPairButton = pairButton;

            // Save the flyout and set to null so it doesn't pop up unless we want it
            ViewModel.SavedPairButtonFlyout       = pairButton.Flyout;
            ViewModel.InProgressPairButton.Flyout = null;

            // Disable the pair button until we are done
            pairButton.IsEnabled = false;

            // Get ceremony type and protection level selections
            DevicePairingKinds ceremoniesSelected = ViewModel.GetSelectedCeremonies();
            // Get protection level
            DevicePairingProtectionLevel protectionLevel = DevicePairingProtectionLevel.Default;

            // Specify custom pairing with all ceremony types and protection level EncryptionAndAuthentication
            DeviceInformationCustomPairing customPairing = deviceInfoDisp.DeviceInformation.Pairing.Custom;

            customPairing.PairingRequested += ViewModel.PairingRequestedHandler;
            DevicePairingResult result = await customPairing.PairAsync(ceremoniesSelected, protectionLevel);

            if (result.Status == DevicePairingResultStatus.Paired)
            {
                formatString        = loader.GetString("BluetoothPairingSuccess/Text");
                confirmationMessage = formatString + deviceInfoDisp.Name + " (" + deviceInfoDisp.Id + ")";
            }
            else
            {
                formatString        = loader.GetString("BluetoothPairingFailure/Text");
                confirmationMessage = formatString + deviceInfoDisp.Name + " (" + deviceInfoDisp.Id + ")"; // result.Status.ToString()
            }
            // Display the result of the pairing attempt
            ViewModel.DisplayMessagePanelAsync(confirmationMessage, SettingBluetoothViewModel.MessageType.InformationalMessage);

            // If the watcher toggle is on, clear any devices in the list and stop and restart the watcher to ensure state is reflected in list
            if (SwitchBluetooth.IsChecked.Value)
            {
                ViewModel.BluetoothDevices.Clear();
                ViewModel.StopWatcher();
                ViewModel.StartWatcher();
            }
            else
            {
                // If the watcher is off this is an inbound request so just clear the list
                ViewModel.BluetoothDevices.Clear();
            }

            // Re-enable the pair button
            ViewModel.InProgressPairButton = null;
            pairButton.IsEnabled           = true;
        }