11,584 questions
AmBle.Bluetooth.Service
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I wrote the following code to scan nearby Bluetooth device. But I found pairing failed if calling Nus.IsSupport() in watcher.Added() function and pairing successfully without calling Nus.IsSupport() in watcher.Added() function. Do you have suggestion to fix this issue?
internal sealed class DeviceWatcher
{
private readonly Windows.Devices.Enumeration.DeviceWatcher watcher;
private readonly AutoResetEvent watcherStoppedEvent = new(false);
private List<Windows.Devices.Enumeration.DeviceInformation> devices;
public DeviceWatcher(AsqFilter filter)
{
watcher = Windows.Devices.Enumeration.DeviceInformation.CreateWatcher(filter.Query,
null,
Windows.Devices.Enumeration.DeviceInformationKind.AssociationEndpoint);
watcher.Added += (_, info) =>
{
if (String.Compare(info.Name, "") == 0)
{
return;
}
// calling Nus.IsSupport() caused pairing failed
devices.Add(info);
};
watcher.Removed += (_, removedDevice) =>
{
try
{
var tempDevices = new List<Windows.Devices.Enumeration.DeviceInformation>(devices);
foreach (var device in devices)
{
if (device.Id == removedDevice.Id)
{
tempDevices.Remove(device);
}
}
devices = tempDevices;
}
catch (Exception ex)
{
Console.WriteLine($"Failed: {ex.Message}");
}
};
watcher.Updated += (_, updatedDevice) =>
{
foreach (var device in devices.Where(device => device.Id == updatedDevice.Id))
{
device.Update(updatedDevice);
}
};
watcher.Stopped += (_, _) => watcherStoppedEvent.Set();
}
public void Start()
{
Console.WriteLine("watcher start");
devices = new();
watcher.Start();
}
public IEnumerable<Windows.Devices.Enumeration.DeviceInformation> Stop()
{
watcher.Stop();
var receivedSignal = watcherStoppedEvent.WaitOne(5 * 1000);
if (!receivedSignal)
{
Console.WriteLine("Warning: the watcher didn't stop after 5 seconds");
}
return devices;
}
}
}
AmBle.Bluetooth.Service