//https://stackoverflow.com/questions/45191412/deviceinformation-pairasync-not-working-in-wpf private async Task DoUnPairing(BTDeviceInfo info) { try { using (BluetoothDevice device = await BluetoothDevice.FromIdAsync(info.Address)) { this.log.Info("DoUnPairing", () => string.Format("'{0}'", info.Name)); DeviceUnpairingResult result = await device.DeviceInformation.Pairing.UnpairAsync(); this.log.Info("DoUnPairing", () => string.Format("'{0}' Unpair status {1}", info.Name, result.Status.ToString())); this.BT_UnPairStatus?.Invoke(this, new BTUnPairOperationStatus() { Name = info.Name, UnpairStatus = result.Status.ConvertStatus(), IsSuccessful = result.Status.IsSuccessful(), }); } } catch (Exception e) { WrapErr.SafeAction(() => { this.BT_UnPairStatus?.Invoke(this, new BTUnPairOperationStatus() { Name = info.Name, UnpairStatus = BT_UnpairingStatus.Failed, IsSuccessful = false, }); }); } }
private async Task<int> unpair_ganglion_async () { if (ganglion_info == null) { return (int)CustomExitCodes.GANGLION_NOT_FOUND_ERROR; } if (ganglion_device == null) { return (int)CustomExitCodes.GANGLION_IS_NOT_OPEN_ERROR; } DeviceUnpairingResult result = null; DeviceInformationPairing pairing_information = ganglion_device.DeviceInformation.Pairing; try { if (pairing_information.IsPaired) { result = await ganglion_device.DeviceInformation.Pairing.UnpairAsync ().AsTask ().TimeoutAfter (timeout); } else { return (int)CustomExitCodes.GANGLION_IS_NOT_PAIRED_ERROR; } } catch (TimeoutException e) { return (int)CustomExitCodes.TIMEOUT_ERROR; } catch (Exception e) { return (int)CustomExitCodes.GENERAL_ERROR; } return (int)CustomExitCodes.STATUS_OK; }
static async Task <bool> Unpair(AnkiBLE.anki_vehicle vehicle) { BluetoothLEDevice device = await BluetoothLEDevice.FromBluetoothAddressAsync(vehicle.mac_address); DeviceUnpairingResult result = await device.DeviceInformation.Pairing.UnpairAsync(); return(result.Status == DeviceUnpairingResultStatus.Unpaired); }
private async void btnUnpair_Click(object sender, RoutedEventArgs e) { var discoveredDevice = (DiscoveredDevice)lvDiscoveredDevices.SelectedItem; DeviceUnpairingResult result = await discoveredDevice.DeviceInfo.Pairing.UnpairAsync(); rootPage.NotifyUser($"Unpair result: {result.Status}", NotifyType.StatusMessage); }
private async void BtUnpair() { rootPage.StatusBar("Paring Started Please Wait...", BarStatus.Warnning); Btdevice deviceInfoDisp = resultListView.SelectedItem as Btdevice; DeviceUnpairingResult dupr = await deviceInfoDisp.DeviceInformation.Pairing.UnpairAsync(); rootPage.StatusBar("Unparing Result" + dupr.Status.ToString(), dupr.Status == DeviceUnpairingResultStatus.Unpaired ? BarStatus.Sucess : BarStatus.Error); }
private static async void Unpair(DeviceInformation device) { // var res = device.Pairing.UnpairAsync().GetAwaiter().GetResult().Status; DeviceUnpairingResult res = await device.Pairing.UnpairAsync(); if (res.Status != DeviceUnpairingResultStatus.Unpaired) { throw new Exception($"Failed to unpair the device. Status = {res.Status}"); } }
public async Task <bool> UnpairingDeviceAsync(string deviceId) { var device = FindKnownBluetoothDevice(deviceId); // do unpairing DeviceUnpairingResult unpairingResult = await device.DeviceInformation.Pairing.UnpairAsync(); if (unpairingResult.Status == DeviceUnpairingResultStatus.Unpaired) { return(true); } return(false); }
private async void UnpairButton_Click(object sender, RoutedEventArgs e) { DeviceInformationDisplay deviceInfoDisp = resultsListView.SelectedItem as DeviceInformationDisplay; Debug.WriteLine("Unpair"); UnpairButton.IsEnabled = false; SensorList.IsEnabled = false; InitButton.IsEnabled = false; EnableButton.IsEnabled = false; EnableIOButton.IsEnabled = false; DisableIOButton.IsEnabled = false; AllOffIOButton.IsEnabled = false; BUZZButton.IsEnabled = false; LED1Button.IsEnabled = false; LED2Button.IsEnabled = false; DeviceInfoConnected = null; Debug.WriteLine("Disable Sensors"); for (int i = 0; i < CC2650SensorTag.NUM_SENSORS; i++) { if (CC2650SensorTag.ServiceList[i] != null) { //await disableSensor(i); await CC2650SensorTag.SensorsCharacteristicsList[i].DisableNotify(); } } Debug.WriteLine("UnpairAsync"); try { DeviceUnpairingResult dupr = await deviceInfoDisp.DeviceInformation.Pairing.UnpairAsync(); string unpairResult = $"Unpairing result = {dupr.Status}"; Debug.WriteLine(unpairResult); UserOut.Text = unpairResult; } catch (Exception ex) { Debug.WriteLine("Unpair exception = " + ex.Message); } for (int i = 0; i < CC2650SensorTag.ServiceList.Length; i++) { CC2650SensorTag.ServiceList[i] = null; } UpdatePairingButtons(); StartWatcher(); }
private Task StopBLEWatcherAsync(DeviceInformationDisplay deviceInfoDisp) { return(Task.Run(async() => { Debug.WriteLine("Disable Sensors"); foreach (var sensor in _serviceList) { await disableSensor(sensor.Key); } lock (_serviceList) { _serviceList.Clear(); } lock (_notifyList) { _notifyList.Clear(); } // stop BLE watcher if (null != blewatcher) { // Unregister all event handlers but stopped, // stop the watcher and wait it is stopped. blewatcher.Added -= OnBLEAdded; blewatcher.Updated -= OnBLEUpdated; blewatcher.Removed -= OnBLERemoved; blewatcher.Stop(); if (blewatcherStopped.WaitOne(TimeSpan.FromMinutes(BLEWATCHER_STOP_TIMEOUT))) { Debug.WriteLine($"BLE watcher {blewatcher.Status.ToString()}"); blewatcher.Stopped -= OnBLEStopped; blewatcher = null; } else { Debug.WriteLine($"CANNOT stop BLE watcher - timeout expired - BLE status: {blewatcher.Status.ToString()}"); } } Debug.WriteLine("UnpairAsync"); DeviceUnpairingResult dupr = await deviceInfoDisp.DeviceInformation.Pairing.UnpairAsync(); string unpairResult = $"Unpairing result = {dupr.Status}"; Debug.WriteLine(unpairResult); await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () => { UserOut.Text = unpairResult; }); })); }
public async Task <bool> Unpair() { DeviceUnpairingResult duResult = await bluetoothLEDevice.DeviceInformation.Pairing.UnpairAsync(); Console.WriteLine("Unpair result: " + duResult.Status); if (duResult.Status == DeviceUnpairingResultStatus.Unpaired) { return(true); } else { return(false); } }
private async void btnUnpair_Click(object sender, RoutedEventArgs e) { var discoveredDevice = (DiscoveredDevice)lvDiscoveredDevices.SelectedItem; if (discoveredDevice == null) { rootPage.NotifyUser("No device selected, please select one.", NotifyType.ErrorMessage); return; } DeviceUnpairingResult result = await discoveredDevice.DeviceInfo.Pairing.UnpairAsync(); rootPage.NotifyUser($"Unpair result: {result.Status}", NotifyType.StatusMessage); }
//private async void btnPair_Click(object sender, RoutedEventArgs e) //{ // resultsListView.IsEnabled = false; // (sender as Button).IsEnabled = false; // this.NotifyUser("Pairing started. Please wait...", NotifyType.StatusMessage); // // Get the device selected for pairing // BluetoothLEDeviceDisplay deviceInfoDisp = resultsListView.SelectedItem as BluetoothLEDeviceDisplay; // DevicePairingResult result = null; // result = await deviceInfoDisp.DeviceInformation.Pairing.PairAsync(); // this.NotifyUser( // "Pairing result = " + result.Status.ToString(), // result.Status == DevicePairingResultStatus.Paired ? NotifyType.StatusMessage : NotifyType.ErrorMessage); // // UpdateButtons(); // resultsListView.IsEnabled = true; //} private async void btnUnPair_Click(object sender, RoutedEventArgs e) { resultsListView.IsEnabled = false; (sender as Button).IsEnabled = false; this.NotifyUser("Unpairing started. Please wait...", NotifyType.StatusMessage); DeviceUnpairingResult dupr = await deviceInfoDisp.DeviceInformation.Pairing.UnpairAsync(); this.NotifyUser( "Unpairing result = " + dupr.Status.ToString(), dupr.Status == DeviceUnpairingResultStatus.Unpaired ? NotifyType.StatusMessage : NotifyType.ErrorMessage); // UpdateButtons(); resultsListView.IsEnabled = true; }
/// <summary> /// Called to unpair a targeted device /// </summary> /// <param name="unpairButton">Unpair button</param> /// <param name="currentDevice">Displayable information for the targeted device</param> public async Task UnpairDeviceAsync(Button unpairButton, BluetoothDeviceInfo currentDevice) { try { string confirmationMessage = string.Empty; // Disable the unpair button until we are done unpairButton.IsEnabled = false; DeviceUnpairingResult unpairingResult = await currentDevice.DeviceInformation.Pairing.UnpairAsync(); if (unpairingResult.Status == DeviceUnpairingResultStatus.Unpaired) { // Device is unpaired confirmationMessage = string.Format(BluetoothUnpairingSuccessFormat, currentDevice.Name, currentDevice.IdWithoutProtocolPrefix); } else { confirmationMessage = string.Format(BluetoothUnpairingFailureFormat, unpairingResult.Status.ToString(), currentDevice.Name, currentDevice.IdWithoutProtocolPrefix); } // Display the result of the unpairing 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 state is reflected in list if (BluetoothWatcherEnabled) { BluetoothDeviceCollection.Clear(); StopWatcher(); StartWatcherAsync(); } else { // If the watcher is off this is an inbound request so just clear the list BluetoothDeviceCollection.Clear(); } // Enable the unpair button unpairButton.IsEnabled = true; } catch (Exception ex) { LogService.Write(ex.ToString(), LoggingLevel.Error); } }
/// <summary> /// User wants to unpair from the selected device /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void UnpairButton_Click(object sender, RoutedEventArgs e) { // Use the unpair button on the bluetoothDeviceListView.SelectedItem to get the data context BluetoothDeviceInformationDisplay deviceInfoDisp = ((Button)sender).DataContext as BluetoothDeviceInformationDisplay; string formatString; string confirmationMessage; Button unpairButton = sender as Button; // Disable the unpair button until we are done unpairButton.IsEnabled = false; DeviceUnpairingResult unpairingResult = await deviceInfoDisp.DeviceInformation.Pairing.UnpairAsync(); ResourceLoader loader = ResourceLoader.GetForCurrentView(); if (unpairingResult.Status == DeviceUnpairingResultStatus.Unpaired) { // Device is unpaired formatString = loader.GetString("BluetoothUnpairingSuccess/Text"); confirmationMessage = formatString + deviceInfoDisp.Name + " (" + deviceInfoDisp.Id + ")"; } else { formatString = loader.GetString("BluetoothUnpairingFailure/Text"); confirmationMessage = formatString + deviceInfoDisp.Name + " (" + deviceInfoDisp.Id + ")"; // unpairingResult.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 unpair button unpairButton.IsEnabled = true; }
private async void UnpairButton_Click(object sender, RoutedEventArgs e) { // Gray out the unpair button and results view while unpairing is in progress. resultsListView.IsEnabled = false; UnpairButton.IsEnabled = false; rootPage.NotifyUser("Unpairing started. Please wait...", NotifyType.StatusMessage); BluetoothLEDeviceDisplay deviceInfoDisp = resultsListView.SelectedItem as BluetoothLEDeviceDisplay; DeviceUnpairingResult dupr = await deviceInfoDisp.DeviceInformation.Pairing.UnpairAsync(); rootPage.NotifyUser( "Unpairing result = " + dupr.Status.ToString(), dupr.Status == DeviceUnpairingResultStatus.Unpaired ? NotifyType.StatusMessage : NotifyType.ErrorMessage); UpdateButtons(); resultsListView.IsEnabled = true; }
/// <summary> /// User wants to unpair from the selected device /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private async void UnpairButton_Click(object sender, RoutedEventArgs e) { // Use the unpair button on the bluetoothDeviceListView.SelectedItem to get the data context BluetoothDeviceInformationDisplay deviceInfoDisp = ((Button)sender).DataContext as BluetoothDeviceInformationDisplay; string formatString; string confirmationMessage; Button unpairButton = sender as Button; // Disable the unpair button until we are done unpairButton.IsEnabled = false; DeviceUnpairingResult unpairingResult = await deviceInfoDisp.DeviceInformation.Pairing.UnpairAsync(); if (unpairingResult.Status == DeviceUnpairingResultStatus.Unpaired) { // Device is unpaired formatString = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothUnpairingSuccessFormat"); confirmationMessage = string.Format(formatString, deviceInfoDisp.Name, deviceInfoDisp.Id); } else { formatString = BluetoothDeviceInformationDisplay.GetResourceString("BluetoothUnpairingFailureFormat"); confirmationMessage = string.Format(formatString, unpairingResult.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 unpair button unpairButton.IsEnabled = true; }
private async void UnpairButton_Click(object sender, RoutedEventArgs e) { DeviceInformationDisplay deviceInfoDisp = resultsListView.SelectedItem as DeviceInformationDisplay; Debug.WriteLine("Unpair"); UnpairButton.IsEnabled = false; SensorList.IsEnabled = false; EnableButton.IsEnabled = false; DisableButton.IsEnabled = false; DeviceInfoConnected = null; Debug.WriteLine("Disable Sensors"); for (int i = 0; i < NUM_SENSORS; i++) { if (serviceList[i] != null) { await disableSensor(i); } } Debug.WriteLine("UnpairAsync"); try { DeviceUnpairingResult dupr = await deviceInfoDisp.DeviceInformation.Pairing.UnpairAsync(); string unpairResult = $"Unpairing result = {dupr.Status}"; Debug.WriteLine(unpairResult); UserOut.Text = unpairResult; } catch (Exception ex) { Debug.WriteLine("Unpair exception = " + ex.Message); } for (int i = 0; i < NUM_SENSORS; i++) { serviceList[i] = null; } UpdatePairingButtons(); }
private async void PairOrCancelButton_Click(object sender, RoutedEventArgs e) { Button Btn = sender as Button; if (Btn.DataContext is BluetoothDeivceData Device) { if (Btn.Content.ToString() == Globalization.GetString("PairText")) { await PairAsync(Device).ConfigureAwait(false); } else { DeviceUnpairingResult UnPairResult = await Device.DeviceInfo.Pairing.UnpairAsync(); if (UnPairResult.Status == DeviceUnpairingResultStatus.Unpaired || UnPairResult.Status == DeviceUnpairingResultStatus.AlreadyUnpaired) { BluetoothDeviceCollection.Remove(Device); } } } }
// -->> 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; }
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; } } }