我们有手机应用程序托管GATT服务器的服务和特点。在桌面应用程序中,我们尝试使用DeviceWatcher使用UWP API进行搜索。
var deviceWatcher = DeviceInformation.CreateWatcher(
BluetoothLEDevice.GetDeviceSelectorFromPairingState(false),
new List<string>(),
DeviceInformationKind.AssociationEndpoint);
然后我们尝试从设备
获取服务var serviceResult = await device.GetGattServicesForUuidAsync(ServiceId);
但这种做法非常不稳定。找到并连接到设备需要30-60秒。有时它找不到设备或找不到设备但无法获得服务。
此外,我们尝试将设备与PC配对,并仅检查配对或连接的设备
var deviceWatcher = DeviceInformation.CreateWatcher(
BluetoothLEDevice.GetDeviceSelectorFromPairingState(true),
new List<string>(),
DeviceInformationKind.AssociationEndpoint);
但是这位观察者没有发现任何东西。我们尝试了不同的AQS过滤器并得到了相同的结果。
此外,我们尝试使用32feet lib来仅获取成对的连接设备。
var client = new BluetoothClient();
var paired = client.DiscoverDevices(5, true, true, false);
foreach (var bluetoothDeviceInfo in paired)
{
var addressBytes = bluetoothDeviceInfo.DeviceAddress.ToByteArray();
var addr = BitConverter.ToUInt64(addressBytes, 0);
var device = await BluetoothLEDevice.FromBluetoothAddressAsync(addr));
var serviceResult = await device.GetGattServicesForUuidAsync(ServiceId);
}
它运行速度很快并找到手机,但发现设备不包含我们的GATT服务,它的蓝牙地址与DeviceWatcher找到的设备不同。看起来在一部手机上有两个蓝牙设备:第一个设备有我们的BLE服务,第二个是配对但没有服务。
有没有办法配对正确的BLE设备,只搜索配对?
答案 0 :(得分:0)
最后,我发现了如何使用BluetoothLEAdvertisementWatcher直接搜索服务。
_watcher = new BluetoothLEAdvertisementWatcher();
_watcher.ScanningMode = BluetoothLEScanningMode.Active;
_watcher.SignalStrengthFilter = new BluetoothSignalStrengthFilter
{
InRangeThresholdInDBm = -75,
OutOfRangeThresholdInDBm = -76,
OutOfRangeTimeout = TimeSpan.FromSeconds(2),
SamplingInterval = TimeSpan.FromSeconds(2)
};
_watcher.AdvertisementFilter =
new BluetoothLEAdvertisementFilter
{
Advertisement =
new BluetoothLEAdvertisement
{
ServiceUuids =
{
BLEHelper.ServiceId
}
}
};
_watcher.Received += OnWatcherOnReceived;
_watcher.Start();
在OnWatcherOnReceived中,我们可以获得蓝牙地址连接服务并获得特色
private void OnWatcherOnReceived(BluetoothLEAdvertisementWatcher w, BluetoothLEAdvertisementReceivedEventArgs a)
{
// use a.BluetoothAddress to connect to device
}