async void getDevices() { var devices = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()); List <string> dList = new List <string>(); listView1.View = View.Details; listView1.GridLines = true; listView1.FullRowSelect = true; listView1.Clear(); listView1.Columns.Add("Device Name", 150); listView1.Columns.Add("Address", 150); foreach (DeviceInformation di in devices) { BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(di.Id); string[] arr = new string[2]; ListViewItem itm; //add items to ListView arr[0] = bleDevice.Name; arr[1] = bleDevice.BluetoothAddress.ToString(); itm = new ListViewItem(arr); listView1.Items.Add(itm); } }
public async Task StartScanning() { using (_cancellationTokenSource = new CancellationTokenSource()) { var cancellationToken = _cancellationTokenSource.Token; Stopwatch stopwatch = new Stopwatch(); stopwatch.Start(); RaiseScanningStateChanged(true); while (cancellationToken.IsCancellationRequested && stopwatch.Elapsed < TimeSpan.FromSeconds(10)) { foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector())) { BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(di.Id); if (_devices.All(x => x.Address != bleDevice.BluetoothAddress.ToString())) { _devices.Add(ConvertDevice(bleDevice)); } } } RaiseScanningStateChanged(false); } }
/// <summary> /// Populates the device list and initializes all the various models. /// /// Waiting for the async calls to complete takes a while, so we want to call this /// function somewhat sparingly. /// </summary> /// <returns></returns> public static async Task PopulateDeviceListAsync() { // Remove all devices and start from scratch PairedDevices.Clear(); // Asynchronously get all paired/connected bluetooth devices. var infoCollection = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()); // Re-add devices foreach (DeviceInformation info in infoCollection) { // Make sure we don't initialize duplicates if (PairedDevices.FindIndex(device => device.DeviceId == info.Id) >= 0) { continue; } BluetoothLEDevice WRTDevice = await BluetoothLEDevice.FromIdAsync(info.Id); BEDeviceModel deviceM = new BEDeviceModel(); deviceM.Initialize(WRTDevice, info); PairedDevices.Add(deviceM); } /* * FUTURE * * Consider reading one characteristic from each device uncached to trigger a connection to the * device, in case the device does not have notifiable characteristics. * * Also consider registering for DeviceConnectionChangeTrigger, in case a device does not have * notifiable characteristics. But that may be overkill - what's the likelihood that a device * won't have notifiable characteristics? * */ }
/// <summary> /// Callback for the refresh button which populates the devices list /// </summary> private async void refreshDevices_Click(object sender, RoutedEventArgs e) { pairedDevices.Items.Clear(); DeviceInformationCollection set = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()); Debug.WriteLine("BLE devices =====> " + set.Count); messages.Text = "#BLE devices = " + set.Count; foreach (var devInfo in set) { try { Debug.WriteLine("device = " + devInfo.Name + ", " + devInfo.Pairing); BluetoothLEDevice ble = await BluetoothLEDevice.FromIdAsync(devInfo.Id); if (ble != null) { pairedDevices.Items.Add(ble); } else { Debug.WriteLine("windows is confused; found a BLE device-info (" + devInfo.Name + ") but could not find it"); } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } }
private static void ListDevices() { // Query for extra properties you want returned string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" }; DeviceWatcher deviceWatcher = DeviceInformation.CreateWatcher( BluetoothLEDevice.GetDeviceSelector(), //BluetoothLEDevice.GetDeviceSelectorFromPairingState(false), requestedProperties, DeviceInformationKind.AssociationEndpoint); deviceWatcher.Added += (sender, args) => { Console.WriteLine(args.Name + " " + args.Id); var e = args.Properties.GetEnumerator(); while (e.MoveNext()) { Console.WriteLine("[" + e.Current.Key + "]" + e.Current.Value); } }; deviceWatcher.Start(); Thread.Sleep(5 * 1000); deviceWatcher.Stop(); }
private async Task <int> ScanDevice() { try { // bleDevices = await DeviceInformation.FindAllAsync(GattDeviceService.GetDeviceSelectorFromUuid(GattServiceUuids.GenericAccess)); bleDevices = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()); Debug.WriteLine("Found " + bleDevices.Count + " device(s)"); if (bleDevices.Count == 0) { await new MessageDialog("No BLE Devices found - make sure you've paired your device").ShowAsync(); await Windows.System.Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:", UriKind.RelativeOrAbsolute)); } deviceList.ItemsSource = bleDevices; } catch (Exception ex) { //if((uint)ex.HResult == 0x8007048F) //{ // await new MessageDialog("Bluetooth is turned off!").ShowAsync(); //} await new MessageDialog("Failed to find BLE devices: " + ex.Message).ShowAsync(); } return(bleDevices.Count); }
private async void refreshDevices_Click(object sender, RoutedEventArgs e) { pairedDevices.Items.Clear(); foreach (var info in await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector())) { pairedDevices.Items.Add(await BluetoothLEDevice.FromIdAsync(info.Id)); } }
private async void retrieveDevices() { pairedDevicesListView.Items.Clear(); foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector())) { BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(di.Id); pairedDevicesListView.Items.Add(bleDevice); } }
private async void discoverDevices() { foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector())) { BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(di.Id); this.mapDevices.Add(bleDevice.Name, bleDevice); } Notification.UpdateTile(this.mapDevices.Count); }
static async Task <IReadOnlyCollection <BluetoothDevice> > PlatformScanForDevices(RequestDeviceOptions options) { List <BluetoothDevice> devices = new List <BluetoothDevice>(); foreach (var device in await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector())) { devices.Add(await BluetoothLEDevice.FromIdAsync(device.Id)); } return(devices.AsReadOnly()); }
private async static void AllConnectedDevicesAsync() { string filter = BluetoothLEDevice.GetDeviceSelector(); DeviceInformationCollection infos = await DeviceInformation.FindAllAsync(filter); Debug.Log("Found " + infos.Count + " Devices"); foreach (DeviceInformation info in infos) { Debug.Log("Device Name: " + info.Name); } }
public async static Task <List <BluetoothLEDevice> > getLEDevices() { foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector())) { BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(di.Id); // Add the dvice name into the list. LEDevicesList.Add(bleDevice); } return(LEDevicesList); }
static async Task <bool> MainAsync() { try { var deviceWatcher = DeviceInformation.CreateWatcher(BluetoothLEDevice.GetDeviceSelector()); deviceWatcher.Added += DeviceWatcher_Added; //deviceWatcher.Updated += DeviceWatcher_Updated; deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted; Trace.WriteLine("Enumerating devices"); deviceWatcher.Start(); waitHandle.Wait(); Trace.WriteLine("Done"); deviceWatcher.Stop(); if (deviceIds.Count == 0) { Console.WriteLine("Failed to find device with corret mac address"); return(false); } if (deviceIds.Count > 1) { Console.WriteLine("Found multiple devices with mac address"); return(false); } var device = await BluetoothLEDevice.FromIdAsync(deviceIds.First()); //Look up uuid var characteristicHandle = int.Parse(parameters.CharacteristicHandle.Substring(2), NumberStyles.HexNumber); var characteristicUuid = handleMappings[characteristicHandle]; var characteristic = device.GattServices. SelectMany(s => s.GetCharacteristics(characteristicUuid)). FirstOrDefault(); if (characteristic == null) { Console.WriteLine("Failed to find characteristic"); return(false); } if (parameters.Read) { return(await ReadCharacteristic(characteristic)); } else { //Parse write value var data = StringToByteArray(parameters.WriteValue); return(await WriteCharacteristic(characteristic, data)); } } catch (Exception ex) { Console.WriteLine(ex.ToString()); return(false); } }
/// <summary> /// Gets the bike device. /// </summary> /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns> private static async Task <DeviceInformation> GetBluetoothDeviceInfo() { var devices = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()); foreach (var device in devices) { if (device.Name == "MCF-0000000000") { return(device); } } return(null); }
//Finds the devices already paired with the pc and add them to the listview private async void PairedDevices() { DeviceInterfacesOutputLst.Items.Clear(); devices = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()); foreach (var device in devices) { DisplayDeviceInterface(device); } OutputList.Items.Insert(0, "Showing all paired BLE devices"); OutputList.Items.Insert(0, "Select you device and click ''Connect''"); }
/// <summary> /// Finds the first paired bluetooth-device with the given name. /// </summary> /// <param name="deviceIndex">The device index of the device.</param> /// <param name="name">The name of the device to be searched for.</param> /// <returns>The <see cref="DeviceInformation"/> of the device, if found.</returns> /// <exception cref="DeviceNotFoundException">Device with given name not found.</exception> private async Task <DeviceInformation> FindDeviceAsync(int deviceIndex, string name) { DeviceInformationCollection devices = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()); DeviceInformation device = devices.Where(information => information.Name == name).ElementAt(deviceIndex); if (device == default) { throw new DeviceNotFoundException("Couldn't find device. Is it paired?"); } return(device); }
public async void SetupBLE() { txtProgress.Text = "Obtaining BTLE Info..."; var query = BluetoothLEDevice.GetDeviceSelector(); var deviceList = await DeviceInformation.FindAllAsync(query); int count = deviceList.Count(); if (count > 0) { //Assumes default name of the Adafruit Bluefruit LE var deviceInfo = deviceList.Where(x => x.Name == "Adafruit Bluefruit LE").FirstOrDefault(); if (deviceInfo != null) { var bleDevice = await BluetoothLEDevice.FromIdAsync(deviceInfo.Id); var deviceServices = bleDevice.GattServices; txtProgress.Text = "Retrieving service and GATT characteristics..."; var deviceSvc = deviceServices.Where(svc => svc.AttributeHandle == 0x003a).FirstOrDefault(); if (deviceSvc != null) { var characteristics = deviceSvc.GetAllCharacteristics(); _notifyCharacteristic = characteristics.Where(x => x.AttributeHandle == 0x003b).FirstOrDefault(); _writeCharacteristic = characteristics.Where(x => x.AttributeHandle == 0x003e).FirstOrDefault(); _readCharacteristic = characteristics.Where(x => x.AttributeHandle == 0x0040).FirstOrDefault(); _notifyCharacteristic.ValueChanged += NotifyCharacteristic_ValueChanged; await _notifyCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync(GattClientCharacteristicConfigurationDescriptorValue.Notify); txtProgress.Text = "Bluetooth LE Device service and characteristics initialized"; txtBTLEStatus.Text = "Initialized"; txtBTLEStatus.Foreground = new SolidColorBrush(Colors.Green); btnBlue.IsEnabled = true; btnGreen.IsEnabled = true; btnYellow.IsEnabled = true; btnOrange.IsEnabled = true; btnPurple.IsEnabled = true; btnRead.IsEnabled = true; } else { txtInfo.Text = "Custom GATT Service Not Found on the Bluefruit"; } } else { txtInfo.Text = "Adafruit Bluefruit LE not found, is it paired ??"; } } }
private async void ConnectDevice() { //This works only if your device is already paired! foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector())) { BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(di.Id); // Display BLE device name var dialogBleDeviceName = new MessageDialog("BLE Device Name " + bleDevice.Name); await dialogBleDeviceName.ShowAsync(); myDevice = bleDevice; } if (myDevice != null) { int servicesCount = 3;//Fill in the amount of services from your device!!!!! int tryCount = 0; bool connected = false; while (!connected)//This is to make sure all services are found. { tryCount++; serviceResult = await myDevice.GetGattServicesAsync(); if (serviceResult.Status == GattCommunicationStatus.Success && serviceResult.Services.Count >= servicesCount) { connected = true; Debug.WriteLine("Connected in " + tryCount + " tries"); } if (tryCount > 5)//make this larger if faild { Debug.WriteLine("Failed to connect to device "); return; } } if (connected) { for (int i = 0; i < serviceResult.Services.Count; i++) { var service = serviceResult.Services[i]; //This must be the service that contains the Gatt-Characteristic you want to read from or write to !!!!!!!. string myServiceUuid = "0000ffe0-0000-1000-8000-00805f9b34fb"; if (service.Uuid.ToString() == myServiceUuid) { Get_Characteriisics(service); break; } } } } }
/// <summary> /// Connect to the desired device. /// </summary> /// <param name="deviceName"></param> public async void selectDevice(string deviceName) { foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector())) { BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(di.Id); // Check if the name of the device founded is EMU Bridge. if (bleDevice.Name == deviceName) { // Save detected device in the current device variable. currentDevice = bleDevice; break; } } }
public async void selectDevice(string deviceName, string deviceAddress) { //This works only if your device is already paired! foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector())) { BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(di.Id); // Check if the name of the device founded is EMU Bridge. if (bleDevice.Name == deviceName && bleDevice.BluetoothAddress.ToString() == deviceAddress) { // Save detected device in the current device variable. CurrentSelectedDevice = bleDevice; break; } } }
/// <summary> /// 按MAC地址查找系统中配对设备 /// </summary> /// <param name="MAC"></param> public async Task SelectDevice(string MAC) { CurrentDeviceMAC = MAC; CurrentDevice = null; DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()).Completed = async(asyncInfo, asyncStatus) => { if (asyncStatus == AsyncStatus.Completed) { DeviceInformationCollection deviceInformation = asyncInfo.GetResults(); foreach (DeviceInformation di in deviceInformation) { await Matching(di.Id); } } }; }
private async void CheckPairedDevices() { Home.GetCurrent().AddLog("Checking paired devices...", AppLog.LogCategory.Debug); BTDevices.Clear(); pairedDevices = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()); ObservableCollection <BTDevice> temp = new ObservableCollection <BTDevice>(); foreach (var device in pairedDevices) { BTDevices.Add(new BTDevice(device)); //Debug.WriteLine("Found device -" + device.Name + "(" + device.Id + ")"); Home.GetCurrent().AddLog($"Device found: {device.Name} [{device.Id}]", AppLog.LogCategory.Debug); } }
/// <summary> /// Get already paired to device MI Band 2 /// </summary> /// <returns>DeviceInformation with Band data. If device is not paired, returns null</returns> public async Task <DeviceInformation> GetPairedBand() { var devices = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()); DeviceInformation deviceInfo = null; foreach (var device in devices) { if (device.Pairing.IsPaired && device.Name == "MI Band 2") { deviceInfo = device; } } return(deviceInfo); }
public async Task FindConnectedLights() { lights.Clear(); var selector = BluetoothLEDevice.GetDeviceSelector(); var devices = await DeviceInformation.FindAllAsync(selector); foreach (var d in devices) { if (config.Lights.ContainsKey(d.Name)) { var light = await Light.FromBluetoothDevice(d); lights.Add(d.Name, light); } } }
private async void Scan() { var devices = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()); foreach (DeviceInformation device in devices) { sensors.Add(new MetawearSensor { Name = device.Name, Address = device.Id }); } MetawearMacAddresses.ItemsSource = sensors; if (sensors.Count() > 0) { MetawearMacAddresses.SelectedIndex = 0; } }
static int Main(string[] args) { if (args.Length != 1 || !args[0].Equals("lescan", StringComparison.OrdinalIgnoreCase)) { Console.WriteLine("Only supports lescan option"); return(1); } var deviceWatcher = DeviceInformation.CreateWatcher(BluetoothLEDevice.GetDeviceSelector()); deviceWatcher.Added += DeviceWatcher_Added; //deviceWatcher.Updated += DeviceWatcher_Updated; deviceWatcher.EnumerationCompleted += DeviceWatcher_EnumerationCompleted; Trace.WriteLine("Enumerating devices"); deviceWatcher.Start(); waitHandle.Wait(); Trace.WriteLine("Done"); deviceWatcher.Stop(); return(0); }
/// <summary> /// 按MAC地址查找系统中配对设备 /// </summary> /// <param name="MAC"></param> public async Task SelectDevice(string MAC) { CurrentDeviceMAC = MAC; CurrentDevice = null; DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()).Completed = async(asyncInfo, asyncStatus) => { if (asyncStatus == AsyncStatus.Completed) { DeviceInformationCollection deviceInformation = asyncInfo.GetResults(); foreach (DeviceInformation di in deviceInformation) { await Matching(di.Id); } if (CurrentDevice == null) { string msg = "没有发现设备"; ValueChanged(MsgType.NotifyTxt, msg); StartBleDeviceWatcher(); } } }; }
public async void StartScanningForDevices(Guid serviceUuid) { if (isScanning == true) { return; } discoveredDevices = new List <IDevice>(); Debug.WriteLine("Adapter: Starting a scan for devices."); //clear the list discoveredDevices = new List <IDevice>(); isScanning = true; foreach (DeviceInformation di in await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector())) { BluetoothLEDevice bleDevice = await BluetoothLEDevice.FromIdAsync(di.Id); if (!DeviceExistsInDiscoveredList(bleDevice)) { var d = new Device(bleDevice); discoveredDevices.Add(d); DeviceDiscovered(this, new DeviceDiscoveredEventArgs() { Device = d }); } if (isScanning == false) { break; } } isScanning = false; }
public async Task startBLEWatcher(int seconds) { // 1. Setup search timer // 2. Loop through all paired devices and unpair them (BLAST YOU MS!) // 3. Clear discovered device lists. // 4. Start the search for unpaired devices. bleSearchTimer.Interval = new TimeSpan(0, 0, 0, seconds); var selector = BluetoothLEDevice.GetDeviceSelector(); var devices = await DeviceInformation.FindAllAsync(selector); // Hacker fix. Each time the app closes the "User Session Token" for the BLE connection // is lost. To re-enable it for our new session, pairing and unpairing must be done. for (int i = 0; i < devices.Count; i++) { await devices[i].Pairing.UnpairAsync(); } clearBleSearchResults(); bleSearchTimer.Start(); bleAdvertWatcher.Start(); }
private async Task <bool> retrieveBoard() { DeviceInformationCollection set = await DeviceInformation.FindAllAsync(BluetoothLEDevice.GetDeviceSelector()); foreach (var devInfo in set) { try { Debug.WriteLine("device = " + devInfo.Name + ", " + devInfo.Pairing); if (devInfo.Name.Contains("MetaWear")) { BluetoothLEDevice selectedDevice = await BluetoothLEDevice.FromIdAsync(devInfo.Id); if (selectedDevice != null) { var newBoard = MetaWearBoard.getMetaWearBoardInstance(selectedDevice); var initResult = await newBoard.Initialize(); if (initResult == 0) { board = newBoard.cppBoard; return(true); } } else { Debug.WriteLine("windows is confused; found a BLE device-info (" + devInfo.Name + ") but could not find it"); } } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } return(false); }