private void StartBluetoothDeviceWatcher() { //// Additional properties we would like about the device. //// Property strings are documented here https://msdn.microsoft.com/en-us/library/windows/desktop/ff521659(v=vs.85).aspx //string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected", "System.Devices.Aep.Bluetooth.Le.IsConnectable" }; //// BT_Code: Example showing paired and non-paired in a single query. //string aqsAllBluetoothLEDevices = "(System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\")"; //DeviceWatcher = // DeviceInformation.CreateWatcher( // aqsAllBluetoothLEDevices, // requestedProperties, // DeviceInformationKind.AssociationEndpoint); //var selector = BluetoothDevice.GetDeviceSelector(); var selector = BluetoothDevice.GetDeviceSelectorFromPairingState(true); DeviceWatcher = DeviceInformation.CreateWatcher(selector, null, DeviceInformationKind.AssociationEndpoint); // Register event handlers before starting the watcher. DeviceWatcher.Added += DeviceWatcher_Added; DeviceWatcher.Updated += DeviceWatcher_Updated; DeviceWatcher.Removed += DeviceWatcher_Removed; DeviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted; DeviceWatcher.Stopped += DeviceWatcher_Stopped; // Start over with an empty collection. KnownDeviceList.Clear(); // Start the watcher. DeviceWatcher.Start(); }
public MainPage() { this.InitializeComponent(); //deviceWatcher = // DeviceInformation.CreateWatcher( // BluetoothDevice.GetDeviceSelectorFromPairingState(true), // requestedProperties, // DeviceInformationKind.AssociationEndpoint); deviceWatcher = DeviceInformation.CreateWatcher( BluetoothDevice.GetDeviceSelectorFromPairingState(true)); //deviceWatcher = // DeviceInformation.CreateWatcher( // BluetoothLEDevice.GetDeviceSelectorFromPairingState(false), // requestedProperties, // DeviceInformationKind.AssociationEndpoint); deviceWatcher.Added += DeviceWatcher_Added; deviceWatcher.Removed += DeviceWatcher_Removed; deviceWatcher.Updated += DeviceWatcher_Updated; deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted; deviceWatcher.Stopped += DeviceWatcher_Stopped; }
public void SearchBluetoothDevice(TextBlock textBlock) { /*string[] requestedProperties = new string[] { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" }; * * DeviceWatcher deviceWatcher = DeviceInformation.CreateWatcher("(System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\")", * requestedProperties, * DeviceInformationKind.AssociationEndpoint);*/ DeviceWatcher deviceWatcher = DeviceInformation.CreateWatcher(BluetoothDevice.GetDeviceSelectorFromPairingState(false)); textBlock.Text = "Available Device List"; deviceWatcher.Added += async(DeviceWatcher sender, DeviceInformation device) => { ListBluetoothID.Add(device.Id); // To update textBlock on UI thread await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync (CoreDispatcherPriority.Normal, () => { // Your UI update code goes here! textBlock.Text += "\n" + device.Id + " " + device.Name; } ); }; deviceWatcher.EnumerationCompleted += (DeviceWatcher sender, object args) => { IsWatchingBluetoothDeviceCompleted = true; }; deviceWatcher.Start(); }
public static AsqFilter NonPairedBluetoothDevicesFilter() { var bNonPaired = BluetoothDevice.GetDeviceSelectorFromPairingState(false); var bleNonPaired = BluetoothLEDevice.GetDeviceSelectorFromPairingState(false); return(new AsqFilter($"({bNonPaired}) OR ({bleNonPaired})")); }
/// <summary>Discover devices</summary> /// <param name="paired">If discovery limited to paired or non paired devices</param> private async void DoDiscovery(bool paired) { try { DeviceInformationCollection devices = await DeviceInformation.FindAllAsync( BluetoothDevice.GetDeviceSelectorFromPairingState(paired)); foreach (DeviceInformation info in devices) { try { this.log.Info("DoDiscovery", () => string.Format("Found device {0}", info.Name)); BTDeviceInfo deviceInfo = new BTDeviceInfo() { Name = info.Name, Connected = false, Address = info.Id, }; using (BluetoothDevice device = await BluetoothDevice.FromIdAsync(info.Id)) { deviceInfo.Connected = device.ConnectionStatus == BluetoothConnectionStatus.Connected; deviceInfo.CanPair = this.GetBoolProperty(device.DeviceInformation.Properties, KEY_CAN_PAIR, false); deviceInfo.IsPaired = this.GetBoolProperty(device.DeviceInformation.Properties, KEY_IS_PAIRED, false); // Container Id also //device.DeviceAccessInformation.CurrentStatus == DeviceAccessStatus. // Allowed, denied by user, by system, unspecified //device.DeviceInformation.EnclosureLocation.; // Dock, lid, panel, etc //device.DeviceInformation.IsDefault; //device.DeviceInformation.IsEnabled; //device.DeviceInformation.Kind == //AssociationEndpoint, Device, etc //device.DeviceInformation.Properties if (device.ClassOfDevice != null) { deviceInfo.DeviceClassInt = (uint)device.ClassOfDevice.MajorClass; deviceInfo.DeviceClassName = string.Format("{0}:{1}", device.ClassOfDevice.MajorClass.ToString(), device.ClassOfDevice.MinorClass.ToString()); //device.ClassOfDevice.ServiceCapabilities == BluetoothServiceCapabilities.ObjectTransferService, etc } // Serial port service name // Bluetooth#Bluetooth10:08:b1:8a:b0:02-20:16:04:07:61:01#RFCOMM:00000000:{00001101-0000-1000-8000-00805f9b34fb} // TODO - determine if all the info in device is disposed by the device.Dispose } // end of using (device) this.DeviceDiscovered?.Invoke(this, deviceInfo); } catch (Exception ex2) { this.log.Exception(9999, "", ex2); } } this.DiscoveryComplete?.Invoke(this, true); } catch (Exception e) { this.log.Exception(9999, "", e); this.DiscoveryComplete?.Invoke(this, false); } }
public static IAsyncOperation <IEnumerable <DeviceInfo> > GetDevices() { return(AsyncInfo.Run(async(cancel) => { var selector = BluetoothDevice.GetDeviceSelectorFromPairingState(true); var devices = await DeviceInformation.FindAllAsync(selector); return devices.Select(d => new DeviceInfo { Name = d.Name, Device = d }); })); }
private void StartWatcher() { RunButton.IsEnabled = false; ResultCollection.Clear(); deviceWatcher = DeviceInformation.CreateWatcher(BluetoothDevice.GetDeviceSelectorFromPairingState(true)); deviceWatcher.Added += OnWatcherDeviceAdded; deviceWatcher.Updated += OnWatcherUpdated; deviceWatcher.Removed += OnWatcherRemoved; deviceWatcher.Stopped += OnWatcherStopped; deviceWatcher.Start(); StopButton.IsEnabled = true; }
IReadOnlyCollection <BluetoothDeviceInfo> DoDiscoverDevices(int maxDevices) { List <BluetoothDeviceInfo> results = new List <BluetoothDeviceInfo>(); var devices = DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelectorFromPairingState(false)).GetResults(); foreach (var device in devices) { var bluetoothDevice = BluetoothDevice.FromIdAsync(device.Id).GetResults(); results.Add(bluetoothDevice); } return(results.AsReadOnly()); }
IEnumerable <BluetoothDeviceInfo> GetPairedDevices() { var t = DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelectorFromPairingState(true)); t.AsTask().ConfigureAwait(false); t.AsTask().Wait(); var devices = t.GetResults(); foreach (var device in devices) { var td = BluetoothDevice.FromIdAsync(device.Id).AsTask(); td.Wait(); var bluetoothDevice = td.Result; yield return(bluetoothDevice); } yield break; }
private async void Button1_Click(object sender, EventArgs e) { var picker = new DevicePicker(); picker.DeviceSelected += Picker_DeviceSelected; picker.Filter.SupportedDeviceSelectors.Add( BluetoothDevice.GetDeviceSelectorFromPairingState(false)); // sync // picker.Show(new Windows.Foundation.Rect(100, 100, 500, 500)); // async DeviceInformation di = await picker.PickSingleDeviceAsync(new Windows.Foundation.Rect(0, 0, 0, 0), Windows.UI.Popups.Placement.Default); if (di == null) { return; } if (di.Pairing.IsPaired == false) { di.Pairing.Custom.PairingRequested += Custom_PairingRequested; if (di.Pairing.CanPair == true) { var pairResult = await di.Pairing.PairAsync(); if (pairResult.Status == DevicePairingResultStatus.Paired) { // do something } } else { var pairResult = await di.Pairing.Custom.PairAsync(DevicePairingKinds.ProvidePin); if (pairResult.Status == DevicePairingResultStatus.Paired) { // do something } } } }
public void StartSearchingForDevice() { #if WINDOWS_UWP var requestedProperties = new string[] { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" }; // var aqs = BluetoothLEDevice.GetDeviceSelectorFromPairingState(false); var aqs = BluetoothDevice.GetDeviceSelectorFromPairingState(false); m_deviceWatcher = DeviceInformation.CreateWatcher( aqs, requestedProperties, DeviceInformationKind.AssociationEndpoint); m_deviceWatcher.Added += OnDeviceAdded; m_deviceWatcher.Removed += OnDeviceLost; m_deviceWatcher.Updated += OnDeviceUpdated; m_deviceWatcher.EnumerationCompleted += OnInitialEnumerationCompleted; m_deviceWatcher.Stopped += OnStopped; m_deviceWatcher.Start(); #endif }
public async void IsPhoneDetected(string btId) { phoneIsDetected = false; var btDevices = await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelectorFromPairingState(false)); foreach (var d in btDevices) { if (d.Id == btId) { phoneIsDetected = true; } } if (phoneIsDetected) { startCaptureProcess(); } else { stopCaptureProcess(); } }
public void When_GetSelector() { string testSelector; testSelector = _deviceSelectorPrefix + "(System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True OR " + _deviceSelectorIssueInquiry + "#False)"; Assert.AreEqual(testSelector, BluetoothDevice.GetDeviceSelector()); testSelector = _deviceSelectorPrefix + "(System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#True OR " + _deviceSelectorIssueInquiry + "#False)"; Assert.AreEqual(testSelector, BluetoothDevice.GetDeviceSelectorFromPairingState(true)); testSelector = _deviceSelectorPrefix + "(System.Devices.Aep.IsPaired:=System.StructuredQueryType.Boolean#False OR " + _deviceSelectorIssueInquiry + "#True)"; Assert.AreEqual(testSelector, BluetoothDevice.GetDeviceSelectorFromPairingState(false)); testSelector = _deviceSelectorPrefix + "(System.Devices.Aep.IsConnected:=System.StructuredQueryType.Boolean#True OR " + _deviceSelectorIssueInquiry + "#False)"; Assert.AreEqual(testSelector, BluetoothDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected)); testSelector = _deviceSelectorPrefix + "(System.Devices.Aep.IsConnected:=System.StructuredQueryType.Boolean#False OR " + _deviceSelectorIssueInquiry + "#True)"; Assert.AreEqual(testSelector, BluetoothDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Disconnected)); string deviceName = "TESTNAME"; testSelector = _deviceSelectorPrefix + "(System.ItemNameDisplay:=\"" + deviceName + "\" OR " + _deviceSelectorIssueInquiry + "#True)"; Assert.AreEqual(testSelector, BluetoothDevice.GetDeviceSelectorFromDeviceName(deviceName)); }
private void StartWatcher() { string aqsFilter; ResultCollection.Clear(); // Request the IsPaired property so we can display the paired status in the UI string[] requestedProperties = { "System.Devices.Aep.IsPaired" }; //for bluetooth LE Devices //aqsFilter = "System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\""; Debug.WriteLine(BluetoothDevice.GetDeviceSelectorFromPairingState(false)); aqsFilter = "System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a263b43f0f974}\""; try { deviceWatcher = DeviceInformation.CreateWatcher(DeviceClass.All); //BluetoothDevice.GetDeviceSelectorFromPairingState(false), //requestedProperties, //DeviceInformationKind.AssociationEndpoint //); } catch (Exception ex) { Debug.WriteLine(ex.Message); } // Hook up handlers for the watcher events before starting the watcher handlerAdded = new TypedEventHandler <DeviceWatcher, DeviceInformation>(async(watcher, deviceInfo) => { // Since we have the collection databound to a UI element, we need to update the collection on the UI thread. await this.Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { ResultCollection.Add(new DeviceInformationDisplay(deviceInfo)); }); }); deviceWatcher.Added += handlerAdded; handlerUpdated = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) => { // Since we have the collection databound to a UI element, we need to update the collection on the UI thread. await Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { // 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 (DeviceInformationDisplay deviceInfoDisp in ResultCollection) { if (deviceInfoDisp.Id == deviceInfoUpdate.Id) { deviceInfoDisp.Update(deviceInfoUpdate); break; } } }); }); deviceWatcher.Updated += handlerUpdated; handlerRemoved = new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) => { // Since we have the collection databound to a UI element, we need to update the collection on the UI thread. await Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { // Find the corresponding DeviceInformation in the collection and remove it foreach (DeviceInformationDisplay deviceInfoDisp in ResultCollection) { if (deviceInfoDisp.Id == deviceInfoUpdate.Id) { ResultCollection.Remove(deviceInfoDisp); break; } } }); }); deviceWatcher.Removed += handlerRemoved; handlerEnumCompleted = new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) => { await Dispatcher.RunAsync(CoreDispatcherPriority.Low, () => { string dbg = "Found " + ResultCollection.Count.ToString() + " Bluetooth LE Devices"; Debug.WriteLine(dbg); resultsListView.ItemsSource = ResultCollection; }); }); deviceWatcher.EnumerationCompleted += handlerEnumCompleted; deviceWatcher.Start(); }
public async void ConnectToWiimote() { var found = false; BluetoothAdapter bluetoothAdapter = await BluetoothAdapter.GetDefaultAsync(); do { if (bluetoothAdapter == null) { viewModel.ConsoleLog = "Please connect a bluetooth adapter.\r\n"; await Task.Delay(1000); } bluetoothAdapter = await BluetoothAdapter.GetDefaultAsync(); } while (bluetoothAdapter == null); var bluetoothAddress = BitConverter.GetBytes(bluetoothAdapter.BluetoothAddress); password[0] = bluetoothAddress[0]; password[1] = bluetoothAddress[1]; password[2] = bluetoothAddress[2]; password[3] = bluetoothAddress[3]; password[4] = bluetoothAddress[4]; password[5] = bluetoothAddress[5]; // int i = 0; // char[] g = new char[6]; // foreach (var pSection in password) // { // g[i] = (char) pSection; // i++; // } // var h = g.ToString(); //var selector = BluetoothDevice.GetDeviceSelector(); // Checks for synced/paired wiidevices var selector = BluetoothDevice.GetDeviceSelectorFromPairingState(true); ConsoleWriteLine("Checking for paired wii devices."); var devices = await DeviceInformation.FindAllAsync(selector); { if (devices.Count != 0) { foreach (var device in devices) { if (device.Name.Contains("Nintendo")) { var result = await device.Pairing.UnpairAsync(); if (result.Status != DeviceUnpairingResultStatus.Unpaired) { ConsoleWriteLine("There was a error unpairing a wii device"); } else { ConsoleWriteLine("Succesfully unpaired a wii device"); } } } } } // Checks for new devices selector = BluetoothDevice.GetDeviceSelectorFromPairingState(false); while (!found) { ConsoleWriteLine("Searching for devices"); devices = await DeviceInformation.FindAllAsync(selector); if (devices.Count != 0) { ConsoleWriteLine($"Found {devices.Count} devices."); foreach (var device in devices) { if (device.Name.Contains("Nintendo")) { ConsoleWriteLine("One device is a Wiimote."); device.Pairing.Custom.PairingRequested += Custom_PairingRequested; var pairingResult = await device.Pairing.Custom.PairAsync(DevicePairingKinds.ProvidePin); if (pairingResult.Status != DevicePairingResultStatus.Paired) { ConsoleWriteLine($"Error: {pairingResult.Status.ToString()}"); } else { var blDevice = await BluetoothDevice.FromIdAsync(device.Id); blDevice.ConnectionStatusChanged += BlDevice_ConnectionStatusChanged; ConsoleWriteLine("Waiting 20 seconds in the hope that the device will be installed by then and the connection is not dropped"); await Task.Delay(TimeSpan.FromSeconds(20)); var hidDevice = await HidDevice.FromIdAsync(blDevice.DeviceId, FileAccessMode.ReadWrite); } } } } else { ConsoleWriteLine("Nothing Found."); } await Task.Delay(1000); } }
private async void AppBarButton_Click_1(object sender, RoutedEventArgs e) { try { StoreServicesCustomEventLogger logger = StoreServicesCustomEventLogger.GetDefault(); logger.Log("AddBluetooth"); string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" }; DeviceWatcher deviceWatcher = DeviceInformation.CreateWatcher( BluetoothLEDevice.GetDeviceSelectorFromPairingState(false), requestedProperties, DeviceInformationKind.AssociationEndpoint); // Register event handlers before starting the watcher. // Added, Updated and Removed are required to get all nearby devices // deviceWatcher.Added += DeviceWatcher_Added; // deviceWatcher.Updated += DeviceWatcher_Updated; // deviceWatcher.Removed += DeviceWatcher_Removed; // EnumerationCompleted and Stopped are optional to implement. // deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted; // deviceWatcher.Stopped += DeviceWatcher_Stopped; // Start the watcher. //deviceWatcher.Start(); var displayInformation = Windows.Graphics.Display.DisplayInformation.GetForCurrentView(); double ScreenWidth = 100; double ScreenHeight = 100; if (displayInformation.CurrentOrientation == Windows.Graphics.Display.DisplayOrientations.Portrait) { ScreenWidth = Math.Round(Window.Current.Bounds.Width * displayInformation.RawPixelsPerViewPixel, 0); ScreenHeight = Math.Round(Window.Current.Bounds.Height * displayInformation.RawPixelsPerViewPixel, 0); } if (displayInformation.CurrentOrientation == Windows.Graphics.Display.DisplayOrientations.Landscape) { ScreenWidth = Math.Round(Window.Current.Bounds.Height * displayInformation.RawPixelsPerViewPixel, 0); ScreenHeight = Math.Round(Window.Current.Bounds.Width * displayInformation.RawPixelsPerViewPixel, 0); } // For devices with software buttons instead hardware else if (displayInformation.CurrentOrientation == Windows.Graphics.Display.DisplayOrientations.LandscapeFlipped) { ScreenWidth = Math.Round(Window.Current.Bounds.Height * displayInformation.RawPixelsPerViewPixel, 0); ScreenHeight = Math.Round(Window.Current.Bounds.Width * displayInformation.RawPixelsPerViewPixel, 0); } Rect rect = new Rect(new Point(ScreenHeight, ScreenWidth), new Point(100, 100)); DevicePicker devicePicker = new DevicePicker(); //devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(false)); // devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothLEDevice.GetDeviceSelectorFromPairingState(true)); devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothDevice.GetDeviceSelectorFromPairingState(false)); devicePicker.Filter.SupportedDeviceSelectors.Add(BluetoothDevice.GetDeviceSelectorFromPairingState(true)); var s = await devicePicker.PickSingleDeviceAsync(rect); if (s != null) { var sd = await s.Pairing.PairAsync(); // await new MessageDialog(sd.ToString()+"\n"+ DevicePairingResultStatus.Paired).ShowAsync(); if (sd.Status == DevicePairingResultStatus.Paired || sd.Status == DevicePairingResultStatus.AlreadyPaired || sd.Status == DevicePairingResultStatus.AccessDenied) { //var rfcommServices = await ClassBluetoothDeviceSelect.bluetoothDeviced.GetRfcommServicesForIdAsync(RfcommServiceId.FromUuid(RfcommServiceId.SerialPort.Uuid), BluetoothCacheMode.Uncached); var bluetoothDevice = await BluetoothDevice.FromIdAsync(s.Id); Frame.Navigate(typeof(BlankPageBluettotchDevice), new ClassBluetoothDevice() { namea = s.Name, bluetoothDeviced = bluetoothDevice }); } } } catch (Exception ex) { await new MessageDialog(ex.Message).ShowAsync(); } }
private void uiCreate_Click(object sender, RoutedEventArgs e) { uiResultMsg.Text = "Creating query..."; bool bBLE = (uiBTtype.SelectedValue as ComboBoxItem).Content.ToString().Contains("LE"); switch ((uiQuery.SelectedValue as ComboBoxItem).Content.ToString()) { case "GetDeviceSelector": if (bBLE) { uiResultMsg.Text = BluetoothLEDevice.GetDeviceSelector(); } else { uiResultMsg.Text = BluetoothDevice.GetDeviceSelector(); } break; case "GetDeviceSelectorFromPairingState(true)": if (bBLE) { uiResultMsg.Text = BluetoothLEDevice.GetDeviceSelectorFromPairingState(true); } else { uiResultMsg.Text = BluetoothDevice.GetDeviceSelectorFromPairingState(true); } break; case "GetDeviceSelectorFromPairingState(false)": if (bBLE) { uiResultMsg.Text = BluetoothLEDevice.GetDeviceSelectorFromPairingState(false); } else { uiResultMsg.Text = BluetoothDevice.GetDeviceSelectorFromPairingState(false); } break; case "GetDeviceSelectorFromConnectionStatus(Connected)": if (bBLE) { uiResultMsg.Text = BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected); } else { uiResultMsg.Text = BluetoothDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Connected); } break; case "GetDeviceSelectorFromConnectionStatus(Disconnected)": if (bBLE) { uiResultMsg.Text = BluetoothLEDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Disconnected); } else { uiResultMsg.Text = BluetoothDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Disconnected); } break; default: uiResultMsg.Text = "Unknown value in second ComboBox"; break; } }
private async void RefreshBT(object sender, RoutedEventArgs e) { BtDevices.Items.Clear(); BluetoothDevices.Clear(); Log.Information("Refreshing bluetooth devices."); try { DeviceInformationCollection PairedDevices = await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelectorFromPairingState(true)); Log.Information($"Found {PairedDevices.Count} bluetooth devices."); foreach (var i in PairedDevices) { BluetoothDevices.Add(new BluetoothDevices { DeviceID = i.Id, DeviceName = i.Name, DeviceType = DeviceTypes.Bluetooth }); BtDevices.Items.Add($"{i.Name} ({i.Id})"); Log.Information($"Adding bluetooth device {i.Name} ({i.Id}) into the list."); } btName.Text = ""; if (PairedDevices.Count < 1) { Log.Error("Unable to find any bluetooth devices."); Helper.Error("Error", "Unable to find any bluetooth devices. Make sure you have paired your devices with this computer before and try again."); } } catch (Exception ex) { Log.Error(ex, "Error scanning for bluetooth devices."); Helper.Error("Error", "There was a unknown error scanning for bluetooth devices. Contact the developer"); } }
private void RunButton_Click(object sender, RoutedEventArgs e) { Status.Text = "Looking for nearby devices"; deviceWatcher = DeviceInformation.CreateWatcher(BluetoothDevice.GetDeviceSelectorFromPairingState(false), null); // Hook up handlers for the watcher events before starting the watcher deviceWatcher.Added += new TypedEventHandler <DeviceWatcher, DeviceInformation>(async(watcher, deviceInfo) => { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Make sure device name isn't blank if (deviceInfo.Name != "") { ResultCollection.Add(new AvatarDeviceDisplay(deviceInfo)); System.Diagnostics.Debug.WriteLine(resultsListView.Items.Count); } }); }); deviceWatcher.Updated += new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) => { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { foreach (AvatarDeviceDisplay avatarInfoDisp in ResultCollection) { if (avatarInfoDisp.Id == deviceInfoUpdate.Id) { avatarInfoDisp.Update(deviceInfoUpdate); break; } } }); }); deviceWatcher.EnumerationCompleted += new TypedEventHandler <DeviceWatcher, Object>((watcher, obj) => { }); deviceWatcher.Removed += new TypedEventHandler <DeviceWatcher, DeviceInformationUpdate>(async(watcher, deviceInfoUpdate) => { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Find the corresponding DeviceInformation in the collection and remove it foreach (AvatarDeviceDisplay avatarInfoDisp in ResultCollection) { if (avatarInfoDisp.Id == deviceInfoUpdate.Id) { ResultCollection.Remove(avatarInfoDisp); break; } } }); }); deviceWatcher.Stopped += new TypedEventHandler <DeviceWatcher, Object>(async(watcher, obj) => { await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { // Find the corresponding DeviceInformation in the collection and remove it ResultCollection.Clear(); Status.Text = "Watcher Stopped"; RunButton.IsEnabled = true; }); }); deviceWatcher.Start(); }
private static async Task <string> SelectDevice() { DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelectorFromPairingState(true)); for (int i = 0; i < devices.Count; i++) { Console.WriteLine(i + " #: " + devices[i].Name + " " + devices[i].Id); } Console.WriteLine("Please input device id to select or 'i' for iPhone or 'q' to quit: "); string ent = Console.ReadLine(); if (ent == "i") { return(await SelectiPhone()); } else if (ent == "q") { return("q"); } else { if (int.TryParse(ent, out int s)) { if (s >= 0 && s < devices.Count) { Console.WriteLine("Selected: " + devices[s].Name + " " + devices[s].Id); return(devices[s].Id); } } } return(""); }
private static async Task <string> SelectiPhone() { DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelectorFromPairingState(true)); for (int i = 0; i < devices.Count; i++) { if (devices[i].Name.IndexOf("iphone", StringComparison.CurrentCultureIgnoreCase) != -1) { Console.WriteLine("Selected: " + devices[i].Name + " " + devices[i].Id); return(devices[i].Id); } } Console.WriteLine("No iPhone found."); return(string.Empty); }