Windows 10 - 如何检测蓝牙设备何时在范围内

Windows 10 - how to detect when a Bluetooth device is in range

我之前已经与支持 RFCOMM 的蓝牙设备配对。 当我的应用程序打开时,我不断尝试通过打开 RFCOMM 连接到设备。这样,当设备进入范围时,我的应用程序会自动连接。

deviceInfoCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort));
        LogData(String.Format("Number of mldp devices is {0}", deviceInfoCollection.Count));
        foreach (DeviceInformation deviceInfo in deviceInfoCollection)
        {
            LogData(String.Format("ID:{0}, NAME:{1}", deviceInfo.Id, deviceInfo.Name));
        }

然后 运行 在计时器上执行此操作:

try
            {
                // The first time this method is invoked by a store app, it should be called 
                // from a UI thread in order to display the consent prompt
                // https://msdn.microsoft.com/en-us/windows.devices.bluetooth.rfcomm.rfcommdeviceservice.fromidasync
                RfcommDeviceService rfcommService = await RfcommDeviceService.FromIdAsync(deviceInfo.Id);
                LogData(String.Format("ID:{0}, NAME:{1}", deviceInfo.Id, deviceInfo.Name));
            }
            catch (Exception)
            {
                LogData(String.Format("Can not request rfcomm service from device ID:{0}, NAME:{1}", deviceInfo.Id, deviceInfo.Name));
            }

有什么方法可以查询设备何时在范围内,而不是尝试连接?我宁愿只在设备在范围内时尝试连接。

对于 RFCOMM(BT2.0、BT2.1),您可以 运行 定期枚举设备,另请参阅 Get bluetooth devices in range

但是,您尝试连接的实际实施可能会更好一些。

蓝牙4.0可以收听蓝牙模块的广告,另见https://github.com/Microsoft/Windows-universal-samples/tree/master/Samples/BluetoothAdvertisement

如果您正在与嵌入式设备(例如某些机器人或使用 RFCOMM 的自制设备)通信,恐怕没有比您正在做的更好的解决方案了。

如果您使用 phone(同时支持 BT4.0 和 BT2.1),您可以使用 BT4 广告来指示设备的接近度,然后通过 RFCOMM 连接。