protected static async Task <IDevice1?> ScanAndConnectInternal(ScanFilter filter, TimeSpan?timeout = null, string?adapter = null) { // Default value if (timeout == null) { timeout = TimeSpan.FromSeconds(10); } try { IAdapter1?a; if (adapter == null) { var adapters = await BlueZManager.GetAdaptersAsync(); if (adapters.Count == 0) { Log.Error("No Bluetooth adapters found."); throw new BleDeviceError("No Bluetooth adapters found."); } a = adapters.First(); } else { a = await BlueZManager.GetAdapterAsync(adapter); } var adapterPath = a.ObjectPath.ToString(); var adapterName = adapterPath.Substring(adapterPath.LastIndexOf("/", StringComparison.Ordinal) + 1); Log.Debug($"Using Bluetooth Adapter {adapterName}."); var devices = await a.GetDevicesAsync(); foreach (var device in devices) { var properties = await device.GetAllAsync(); var deviceDescription = await GetDeviceDescriptionAsync(device, properties); Log.Debug(deviceDescription); if (await CheckAndConnect(filter, device)) { return(device); } } Log.Debug($"{devices.Count} device(s) found ahead of scan."); // Scan for more devices. Log.Debug($"Scanning for {timeout.Value.Seconds} seconds..."); IDevice1?device1 = null; var tokenSource = new CancellationTokenSource(); using (await a.WatchDevicesAddedAsync(async device => { var deviceProperties = await device.GetAllAsync(); var deviceDescription = await GetDeviceDescriptionAsync(device, deviceProperties); Log.Debug($"[NEW] {deviceDescription}"); if (!await CheckAndConnect(filter, device)) { return; } device1 = device; Log.Debug("Stopping scan..."); tokenSource.Cancel(); })) { Log.Debug("Starting scanning..."); await a.StartDiscoveryAsync(); await Task.Delay(TimeSpan.FromSeconds(timeout.Value.Seconds), tokenSource.Token); await a.StopDiscoveryAsync(); Log.Debug("Scan complete."); } if (device1 != null) { return(device1); } Log.Warning("Device not found."); } catch (Tmds.DBus.DBusException e) { Log.Warning($"Error: {e.ErrorMessage}."); } return(null); }