Windows UWP 蓝牙应用程序,即使关闭电源,设备也会在扫描时显示

fab*_*ian 5 c# windows bluetooth uwp

我正在开发一个使用蓝牙连接到不同设备的 UWP 应用程序。

我的问题是,一些已配对或先前发现的设备显示在我的设备列表中,即使它们已关闭或不在范围内。

据我了解,属性System.Devices.Aep.IsPresent可用于过滤掉当时不可用的缓存设备,但即使我知道该设备无法访问,我也始终为该属性获取“True”。

关于如何解决这个问题的任何想法?

设置

string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected", "System.Devices.Aep.IsPresent", "System.Devices.Aep.ContainerId", "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.Manufacturer", "System.Devices.Aep.ModelId", "System.Devices.Aep.ProtocolId", "System.Devices.Aep.SignalStrength"};
        _deviceWatcher = DeviceInformation.CreateWatcher("{REMOVED, NOT IMPORTANT}", requestedProperties, DeviceInformationKind.AssociationEndpoint);
        _deviceWatcher.Added += DeviceAdded;
        _deviceWatcher.Updated += DeviceUpdated;
        _deviceWatcher.Removed += DeviceRemoved;
        _deviceWatcher.EnumerationCompleted += DeviceEnumerationCompleted;
Run Code Online (Sandbox Code Playgroud)

添加设备时的回调

这里 isPresent 永远是真的

private void DeviceAdded(DeviceWatcher sender, DeviceInformation deviceInfo)
{
    Device device = new Device(deviceInfo);
    bool isPresent = (bool)deviceInfo.Properties.Single(p => p.Key == "System.Devices.Aep.IsPresent").Value;
    Debug.WriteLine("*** Found device " + deviceInfo.Id + " / " + device.Id + ", " + "name: " + deviceInfo.Name + " ***");
    Debug.WriteLine("RSSI = " + deviceInfo.Properties.Single(d => d.Key == "System.Devices.Aep.SignalStrength").Value);
    Debug.WriteLine("Present: " + isPresent);
    var rssi = deviceInfo.Properties.Single(d => d.Key == "System.Devices.Aep.SignalStrength").Value;
    if (rssi != null)
        device.Rssi = int.Parse(rssi.ToString());
    if (DiscoveredDevices.All(x => x.Id != device.Id) && isPresent)
    {
        DiscoveredDevices.Add(device);
        DeviceDiscovered(this, new DeviceDiscoveredEventArgs(device));
    }
}
Run Code Online (Sandbox Code Playgroud)

xme*_*eko 5

查看Microsoft Bluetooth LE Explorer 源代码GattSampleContext。您需要获取 properties:System.Devices.Aep.IsConnected, System.Devices.Aep.Bluetooth.Le.IsConnectable并仅过滤可连接的设备。请注意,在DeviceWatcher.Updated调用事件后设备可能会变得可连接。所以你必须保持一些跟踪unusedDevices

例如,我的 IsConnactable 过滤器方法是:

private static bool IsConnectable(DeviceInformation deviceInformation)
{
    if (string.IsNullOrEmpty(deviceInformation.Name))
        return false;
    // Let's make it connectable by default, we have error handles in case it doesn't work
    bool isConnectable = (bool?)deviceInformation.Properties["System.Devices.Aep.Bluetooth.Le.IsConnectable"] == true;
    bool isConnected = (bool?)deviceInformation.Properties["System.Devices.Aep.IsConnected"] == true;
    return isConnectable || isConnected;
}
Run Code Online (Sandbox Code Playgroud)