为何Windows 10的DeviceWatcher会检测到不可用的BLE蓝牙设备?
问题描述
在Windows 10系统中使用DeviceWatcher搜索可用的BLE蓝牙设备时,虽能正常识别可用设备,但也会检测到近期搜索过但当前不可用(未开机或超出范围)的设备,重启应用后该现象仍存在。
相关代码
private List<DeviceInformation> Devices = new List<DeviceInformation>(); private DeviceWatcher deviceWatcher; private void StartBleDeviceWatcher() { string[] requestedProperties = { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected", "System.Devices.Aep.Bluetooth.Le.IsConnectable" }; string aqsAllBluetoothLEDevices = "(System.Devices.Aep.ProtocolId:=\"{bb7bb05e-5972-42b5-94fc-76eaa7084d49}\")"; deviceWatcher = DeviceInformation.CreateWatcher(aqsAllBluetoothLEDevices, requestedProperties, DeviceInformationKind.AssociationEndpoint); deviceWatcher.Added += DeviceWatcher_Added; deviceWatcher.Updated += DeviceWatcher_Updated; Devices.Clear(); deviceWatcher.Start(); } private void DeviceWatcher_Updated(DeviceWatcher sender, DeviceInformationUpdate deviceInfo) { } private void DeviceWatcher_Added(DeviceWatcher sender, DeviceInformation deviceInfo) { Devices.Add(deviceInfo); comboBox_AddItem(comboBox_devices, " MAC: " + deviceInfo.Id.Substring(44) + " | Name: " + deviceInfo.Name); }
可能的原因
- AQS查询条件未过滤可连接设备:当前的AQS语句仅筛选了BLE协议的设备,没有加入
System.Devices.Aep.Bluetooth.Le.IsConnectable为true的条件。Windows会缓存过往发现的BLE设备信息,Watcher会默认返回缓存中的设备,不管当前是否可用。 - 未处理设备移除事件:代码仅订阅了
Added和Updated事件,未订阅Removed事件。当设备从可用状态变为不可用时,系统会触发Removed事件通知,但代码没有处理该事件,导致已不可用的设备仍保留在列表中。 - 未校验设备实时可连接状态:虽然请求了
System.Devices.Aep.Bluetooth.Le.IsConnectable属性,但在Added事件中没有判断该属性是否为true,直接将设备加入列表。缓存的设备可能该属性仍为之前的可用状态,或者后续状态更新时Updated事件为空,没有做状态校验和列表更新。 - Windows设备缓存机制:Windows系统会自动缓存已发现的蓝牙设备信息,即使设备当前离线或超出范围,只要缓存未被系统清理(比如未手动删除设备),DeviceWatcher仍会返回这些缓存条目,而代码没有做额外的有效性验证。
内容的提问来源于stack exchange,提问作者JO95
相关产品推荐
相关产品推荐

