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(); } } }
private void ShowPairingPanel(string text, DevicePairingKinds pairingKind) { pairingPanel.Visibility = Visibility.Collapsed; pinEntryTextBox.Visibility = Visibility.Collapsed; okButton.Visibility = Visibility.Collapsed; yesButton.Visibility = Visibility.Collapsed; noButton.Visibility = Visibility.Collapsed; pairingTextBlock.Text = text; switch (pairingKind) { case DevicePairingKinds.ConfirmOnly: case DevicePairingKinds.DisplayPin: // Don't need any buttons break; case DevicePairingKinds.ProvidePin: pinEntryTextBox.Text = ""; pinEntryTextBox.Visibility = Visibility.Visible; okButton.Visibility = Visibility.Visible; break; case DevicePairingKinds.ConfirmPinMatch: yesButton.Visibility = Visibility.Visible; noButton.Visibility = Visibility.Visible; break; } pairingPanel.Visibility = Visibility.Visible; }
/// <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; }
private DevicePairingKinds GetSelectedCeremonies() { DevicePairingKinds ceremonySelection = DevicePairingKinds.None; if (confirmOnlyOption.IsChecked.Value) { ceremonySelection |= DevicePairingKinds.ConfirmOnly; } if (displayPinOption.IsChecked.Value) { ceremonySelection |= DevicePairingKinds.DisplayPin; } if (providePinOption.IsChecked.Value) { ceremonySelection |= DevicePairingKinds.ProvidePin; } if (confirmPinMatchOption.IsChecked.Value) { ceremonySelection |= DevicePairingKinds.ConfirmPinMatch; } if (passwordCredentialOption.IsChecked.Value) { ceremonySelection |= DevicePairingKinds.ProvidePasswordCredential; } return(ceremonySelection); }
/// <summary> /// Get the set of acceptable ceremonies from the check boxes /// </summary> /// <returns>Types of I/O Bluetooth connections supported by the device</returns> private DevicePairingKinds GetSelectedCeremonies() { DevicePairingKinds ceremonySelection = DevicePairingKinds.ConfirmOnly | DevicePairingKinds.DisplayPin | DevicePairingKinds.ProvidePin | DevicePairingKinds.ConfirmPinMatch; return(ceremonySelection); }
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); }
/// <summary> /// Attempts to pair the device. /// </summary> /// <param name="pairingKindsSupported">The different pairing kinds supported by this DeviceInformation object.</param> /// <returns>The result of the pairing action.</returns> public async Task <DevicePairingResult> PairAsync(DevicePairingKinds pairingKindsSupported) { #if WINDOWS_UWP return(await _pairing.PairAsync((Windows.Devices.Enumeration.DevicePairingKinds)((int)pairingKindsSupported))); #elif WIN32 int result = NativeMethods.BluetoothAuthenticateDeviceEx(IntPtr.Zero, IntPtr.Zero, ref _deviceInfo, IntPtr.Zero, 0); return(new DevicePairingResult(result)); #else return(null); #endif }
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 RegisterForInboundPairingRequests() { // Make the system discoverable for Bluetooth await MakeDiscoverable(); // If the attempt to make the system discoverable failed then likely there is no Bluetooth device present // so leave the diagnositic message put uot by the call to MakeDiscoverable() if (App.IsBluetoothDiscoverable) { string formatString; string confirmationMessage; // Get state of ceremony checkboxes DevicePairingKinds ceremoniesSelected = GetSelectedCeremonies(); int iCurrentSelectedCeremonies = (int)ceremoniesSelected; // Find out if we changed the ceremonies we orginally registered with - if we have registered before these will be saved var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; Object supportedPairingKinds = localSettings.Values["supportedPairingKinds"]; int iSavedSelectedCeremonies = -1; // Deliberate impossible value if (supportedPairingKinds != null) { iSavedSelectedCeremonies = (int)supportedPairingKinds; } if (!DeviceInformationPairing.TryRegisterForAllInboundPairingRequests(ceremoniesSelected)) { confirmationMessage = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothInboundRegistrationFailed"); } else { // Save off the ceremonies we registered with localSettings.Values["supportedPairingKinds"] = iCurrentSelectedCeremonies; formatString = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothInboundRegistrationSucceededFormat"); confirmationMessage = string.Format(formatString, ceremoniesSelected.ToString()); } DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage); // Enable the watcher switch BluetoothWatcherToggle.IsEnabled = true; } else { // Disable the watcher switch BluetoothWatcherToggle.IsEnabled = false; } }
async void RegisterForInboundPairingRequests() { // Make the system discoverable for Bluetooth await MakeDiscoverable(); // If the attempt to make the system discoverable failed then likely there is no Bluetooth device present // so leave the diagnositic message put out by the call to MakeDiscoverable() if (App.IsBluetoothDiscoverable) { string formatString; string confirmationMessage; // Get state of ceremony checkboxes DevicePairingKinds ceremoniesSelected = GetSelectedCeremonies(); int iCurrentSelectedCeremonies = (int)ceremoniesSelected; // Find out if we changed the ceremonies we orginally registered with - if we have registered before these will be saved var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings; Object supportedPairingKinds = localSettings.Values["supportedPairingKinds"]; int iSavedSelectedCeremonies = -1; // Deliberate impossible value if (supportedPairingKinds != null) { iSavedSelectedCeremonies = (int)supportedPairingKinds; } ResourceLoader loader = ResourceLoader.GetForCurrentView(); if (!DeviceInformationPairing.TryRegisterForAllInboundPairingRequests(ceremoniesSelected)) { confirmationMessage = loader.GetString("BluetoothInboundRegistrationFailed/Text"); } else { // Save off the ceremonies we registered with localSettings.Values["supportedPairingKinds"] = iCurrentSelectedCeremonies; formatString = loader.GetString("BluetoothInboundRegistrationSucceeded/Text"); confirmationMessage = formatString + ceremoniesSelected.ToString(); } // Clear the current collection BluetoothDevices.Clear(); // Start the watcher StartWatcher(); // Display a message confirmationMessage += loader.GetString("BluetoothOn/Text"); DisplayMessagePanelAsync(confirmationMessage, MessageType.InformationalMessage); } }
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; } }
/// <summary> /// Register the device for inbound pairing requests /// </summary> private async void RegisterForInboundPairingRequests() { // Make the system discoverable for Bluetooth. await MakeDiscoverable(); string confirmationMessage = string.Empty; // If the attempt to make the system discoverable failed then likely there is no Bluetooth device present, // so leave the diagnostic message put up by the call to MakeDiscoverable(). if (_isBluetoothDiscoverable) { // Get state of ceremony checkboxes DevicePairingKinds ceremoniesSelected = GetSelectedCeremonies(); int iCurrentSelectedCeremonies = (int)ceremoniesSelected; int iSavedSelectedCeremonies = -1; // Deliberate impossible value // Find out if we changed the ceremonies we originally registered with. // If we have registered before, these will be saved. object supportedPairingKinds = LocalSettings.Values["supportedPairingKinds"]; if (supportedPairingKinds != null) { iSavedSelectedCeremonies = (int)supportedPairingKinds; } if (!DeviceInformationPairing.TryRegisterForAllInboundPairingRequests(ceremoniesSelected)) { confirmationMessage = string.Format(BluetoothInboundRegistrationFailed, ceremoniesSelected.ToString()); } else { // Save off the ceremonies we registered with LocalSettings.Values["supportedPairingKinds"] = iCurrentSelectedCeremonies; confirmationMessage = string.Format(BluetoothInboundRegistrationSucceededFormat, ceremoniesSelected.ToString()); } BluetoothWatcherEnabled = true; } else { BluetoothWatcherEnabled = false; } await DisplayMessagePanel(confirmationMessage, MessageType.InformationalMessage); }
private void ShowPairingPanel(string text, DevicePairingKinds pairingKind) { switch (pairingKind) { case DevicePairingKinds.ConfirmOnly: case DevicePairingKinds.DisplayPin: // Don't need any buttons break; case DevicePairingKinds.ProvidePin: break; case DevicePairingKinds.ConfirmPinMatch: break; } //pairingPanel.Visibility = Visibility.Visible; }
public async Task <bool> RequestPairDeviceAsync(DeviceInformationPairing pairing) { WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters(); short?groupOwnerIntent = Utils.GetSelectedItemTag <short?>(cmbGOIntent); if (groupOwnerIntent.HasValue) { connectionParams.GroupOwnerIntent = groupOwnerIntent.Value; } DevicePairingKinds devicePairingKinds = DevicePairingKinds.None; if (_supportedConfigMethods.Count > 0) { // If specific configuration methods were added, then use them. foreach (var configMethod in _supportedConfigMethods) { connectionParams.PreferenceOrderedConfigurationMethods.Add(configMethod); devicePairingKinds |= WiFiDirectConnectionParameters.GetDevicePairingKinds(configMethod); } } else { // If specific configuration methods were not added, then we'll use these pairing kinds. devicePairingKinds = DevicePairingKinds.ConfirmOnly | DevicePairingKinds.DisplayPin | DevicePairingKinds.ProvidePin; } connectionParams.PreferredPairingProcedure = Utils.GetSelectedItemTag <WiFiDirectPairingProcedure>(cmbPreferredPairingProcedure); DeviceInformationCustomPairing customPairing = pairing.Custom; customPairing.PairingRequested += OnPairingRequested; DevicePairingResult result = await customPairing.PairAsync(devicePairingKinds, DevicePairingProtectionLevel.Default, connectionParams); if (result.Status != DevicePairingResultStatus.Paired) { //rootPage.NotifyUser($"PairAsync failed, Status: {result.Status}", NotifyType.ErrorMessage); return(false); } return(true); }
public async Task <bool> RequestPairDeviceAsync(DeviceInformationPairing pairing) { WiFiDirectConnectionParameters connectionParams = new WiFiDirectConnectionParameters(); short?groupOwnerIntent = 1; if (groupOwnerIntent.HasValue) { connectionParams.GroupOwnerIntent = groupOwnerIntent.Value; } DevicePairingKinds devicePairingKinds = DevicePairingKinds.None; //if (_supportedConfigMethods.Count > 0) //{ // // If specific configuration methods were added, then use them. // foreach (var configMethod in _supportedConfigMethods) // { // connectionParams.PreferenceOrderedConfigurationMethods.Add(configMethod); // devicePairingKinds |= WiFiDirectConnectionParameters.GetDevicePairingKinds(configMethod); // } //} //else { // If specific configuration methods were not added, then we'll use these pairing kinds. devicePairingKinds = DevicePairingKinds.ConfirmOnly;// | DevicePairingKinds.DisplayPin | DevicePairingKinds.ProvidePin; } connectionParams.PreferredPairingProcedure = WiFiDirectPairingProcedure.GroupOwnerNegotiation; DeviceInformationCustomPairing customPairing = pairing.Custom; customPairing.PairingRequested += OnPairingRequested; DevicePairingResult result = await customPairing.PairAsync(devicePairingKinds, DevicePairingProtectionLevel.Default, connectionParams); if (result.Status != DevicePairingResultStatus.Paired) { StatusBlock.Text = $"PairAsync failed, Status: {result.Status}"; return(false); } return(true); }
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; }
/// <summary> /// 异步启动蓝牙的配对过程 /// </summary> /// <param name="DeviceInfo"></param> /// <returns></returns> private async Task PairAsync(DeviceInformation DeviceInfo) { DevicePairingKinds PairKinds = DevicePairingKinds.ConfirmOnly | DevicePairingKinds.ConfirmPinMatch; DeviceInformationCustomPairing CustomPairing = DeviceInfo.Pairing.Custom; CustomPairing.PairingRequested += CustomPairInfo_PairingRequested; DevicePairingResult PairResult = await CustomPairing.PairAsync(PairKinds, DevicePairingProtectionLevel.EncryptionAndAuthentication); CustomPairing.PairingRequested -= CustomPairInfo_PairingRequested; if (PairResult.Status == DevicePairingResultStatus.Paired) { BluetoothWatcher.Stop(); BluetoothDeviceCollection.Clear(); BluetoothWatcher.Start(); } else { Tips.Text = "配对失败"; } }
/// <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); } }
/// <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; }
internal DevicePairingRequestedEventArgs(DeviceInformation deviceInformation, DevicePairingKinds pairingKind, string pin) { DeviceInformation = deviceInformation; PairingKind = pairingKind; Pin = pin; }
private async Task PairingRequestedHandler2( DevicePairingRequestedEventArgs args, DevicePairingKinds kind) { switch (kind) { case DevicePairingKinds.ConfirmOnly: // Windows itself will pop the confirmation dialog as part of "consent" if this is running on Desktop or Mobile // If this is an App for 'Windows IoT Core' where there is no Windows Consent UX, you may want to provide your own confirmation. args.Accept(); break; case DevicePairingKinds.DisplayPin: // We just show the PIN on this side. The ceremony is actually completed when the user enters the PIN // on the target device. We automatically except here since we can't really "cancel" the operation // from this side. args.Accept(); // No need for a deferral since we don't need any decision from the user await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { ShowPairingPanel( "Please enter this PIN on the device you are pairing with: " + args.Pin, args.PairingKind); }); break; case DevicePairingKinds.ProvidePin: // A PIN may be shown on the target device and the user needs to enter the matching PIN on // this Windows device. Get a deferral so we can perform the async request to the user. var collectPinDeferral = args.GetDeferral(); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { string pin = await GetPinFromUserAsync(); if (!string.IsNullOrEmpty(pin)) { args.Accept(pin); } collectPinDeferral.Complete(); }); break; case DevicePairingKinds.ConfirmPinMatch: // We show the PIN here and the user responds with whether the PIN matches what they see // on the target device. Response comes back and we set it on the PinComparePairingRequestedData // then complete the deferral. var displayMessageDeferral = args.GetDeferral(); await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, async() => { bool accept = await GetUserConfirmationAsync(args.Pin); if (accept) { args.Accept(); } displayMessageDeferral.Complete(); }); break; } }
// -->> 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; }
/// <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; }
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; } } }