/// <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); } }
void listPairedDevices() { listBox1.Items.Clear(); ddump("Local bt mac: " + btr.getLocalBtAddressStr()); btdc = btr.PairedDevices; foreach (BluetoothDevice bd in btdc) { ddump("Found paired device: " + bd.AddressStr + ", '" + bd.Name + "'"); listBox1.Items.Add(bd); } }
/// <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> /// Method to start the Bluetooth watcher /// </summary> /// <returns></returns> private async void StartWatcherAsync() { await Task.Run(() => { // Bluetooth + BluetoothLE string aqsFilter = "System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\" OR " + "System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\""; // Request the IsPaired property so we can display the paired status in the UI string[] requestedProperties = { "System.Devices.Aep.IsPaired" }; // Get the device selector chosen by the UI, then 'AND' it with the 'CanPair' property _deviceWatcher = DeviceInformation.CreateWatcher( aqsFilter, requestedProperties, DeviceInformationKind.AssociationEndpoint); // Hook up handlers for the watcher events before starting the watcher. // An EnumerationCompleted and Stopped handler are not shown here, but also available to use. _handlerAdded = new TypedEventHandler <DeviceWatcher, DeviceInformation>((watcher, currentDevice) => { // Since we have the collection databound to a UI element, we need to update the collection on the UI thread. InvokeOnUIThread(() => { if (currentDevice.Pairing.CanPair || currentDevice.Pairing.IsPaired) { BluetoothDeviceCollection.Add(new BluetoothDeviceInfo(currentDevice)); } }); }); _deviceWatcher.Added += _handlerAdded; _handlerUpdated = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>((watcher, deviceInfoUpdate) => { // Since we have the collection databound to a UI element, we need to update the collection on the UI thread. InvokeOnUIThread(() => { // Find the corresponding updated DeviceInformation in the collection and pass the update object // to the Update method of the existing DeviceInformation. This automatically updates the object // for us. foreach (BluetoothDeviceInfo currentDevice in BluetoothDeviceCollection) { if (currentDevice.Id == deviceInfoUpdate.Id) { currentDevice.Update(deviceInfoUpdate); break; } } }); }); _deviceWatcher.Updated += _handlerUpdated; _handlerRemoved = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>((watcher, deviceInfoUpdate) => { // Since we have the collection databound to a UI element, we need to update the collection on the UI thread. InvokeOnUIThread(() => { // Find the corresponding DeviceInformation in the collection and remove it foreach (BluetoothDeviceInfo currentDevice in BluetoothDeviceCollection) { if (currentDevice.Id == deviceInfoUpdate.Id) { BluetoothDeviceCollection.Remove(currentDevice); break; } } }); }); _deviceWatcher.Removed += _handlerRemoved; // Start the Device Watcher _deviceWatcher.Start(); }); }
/// <summary> /// Clear listed devices, stop a Bluetooth watcher, and display a notification message /// </summary> public async void StopWatcherWithConfirmationAsync() { BluetoothDeviceCollection.Clear(); StopWatcher(); await DisplayMessagePanel(BluetoothStoppedWatching, MessageType.InformationalMessage); }
/// <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); } }