我正在开发一个使用蓝牙连接到不同设备的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;
添加设备时的回调
这是现在总是如此
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));
}
}
解决方法:
查看Microsoft Bluetooth LE Explorer source code of GattSampleContext
.您需要获取属性:System.Devices.Aep.IsConnected,System.Devices.Aep.Bluetooth.Le.IsConnectable并仅过滤可连接的设备.请注意,在调用DeviceWatcher.Updated事件后,设备可能变为可连接.所以你必须保留一些未使用的设备.
例如.我的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;
}