设备ID和地址都是随机的,我无法将它们用于bleDevice = await BluetoothLEDevice.FromIdAsync
或bleDevice = await BluetoothLEDevice.FromBluetoothAddressAsync
。
我想出了两种可能的解决方案:(1)ConnectionStatusChange和(2)Pairing,
但是两种情况我都有问题。
(1)主要问题] >>
在断开连接之前,我先将bleDevice
保存为bleDeviceReconnect
。
然后我退订,配置特性和服务及蓝牙设备,并将它们设置为null。
在重新连接的情况下,我尝试使用的不是bleDevice = await BluetoothLEDevice.FromIdAsync(bleDeviceReconnect.DeviceId)
:
var newSession = GattSession.FromIdAsyn(bleDeviceReconnect.BluetoothDeviceId); newSession.MaintainConnection = true; bleDeviceReconnect.ConnectionStatusChanged += ConnectionStatusChangedHandler;
但是在这种情况下,永远不会调用事件处理程序。
处理程序看起来像这样:
private async void ConnectionStatusChangedHandler(BluetoothLEDevice bluetoothLeDevice, object o) { Debug.WriteLine(bluetoothLeDevice.ConnectionStatus.ToString()) //To check if event comes or not if(bluetoothLeDevice.ConnectionStatus.ToString() == "Conncected") { sList = bluetoothLeDevice.GetGattServicesForUuidAsync(custom service GUID) . . . } }
(2)如果您也可以回答这个问题,那将是很好,但是如果您不知道或不想,则不必这样做
配对是否会使设备ID或地址保持不变?
我首先需要使用上述方法之一来获取Bluetooth LE对象,我可以使用它来查找定制服务(sList = bleDevice.GetGattServicesForUuidAsync
)和特征(cList = sList.Services[0].GetCharacteristicsForUuidAsync
),然后订阅/写入字符集,依此类推。
因此,如果ID或地址更改,则配对没有意义。
如何正确重新连接到BLE设备?
我将非常感谢您的帮助。
编辑
Richard Zhang-MSFT要求我添加一个最小的可运行演示:
((1)Scenario2_Client.xaml
添加2个按钮:[断开连接]和[重新连接]
*断开连接不会立即发生。请至少等待5秒钟,然后再按[Reconncect]
((2)Scenario2_Client.xaml.cs] >>
声明private BluetoothLEDevice bluetoothLeDeviceReconnect
private void Disconnect_btn_Click(object sender, RoutedEventArgs e) { bluetoothLeDeviceReconnect = bluetoothLeDevice; RemoveValueChangedHandler(); selectedCharacteristic?.Service?.Dispose(); selectedCharacteristic = null; service.Dispose(); service = null; bluetoothLeDevice?.Dispose(); bluetoothLeDevice = null; GC.Collect(); } private void Reconnect_btn_Click(object sender, RoutedEventArgs e) { var newSession = GattSession.FromIdAsyn(bluetoothLeDeviceReconnect.BluetoothDeviceId); newSession.MaintainConnection = true; bluetoothLeDeviceReconnect.ConnectionStatusChanged += ConnectionStatusChangedHandler; } private async void ConnectionStatusChangedHandler(BluetoothLEDevice bluetoothLeDevice, object o) { SEE ABOVE }
目前,我已经没时间了,我还无法测试。
莱姆知道这是否不符合我所说的!我将创建一个GitHub帐户,上传我的项目,然后复制链接并将其粘贴到此处。
设备ID和地址都是随机的,我无法在bleDevice = await BluetoothLEDevice.FromIdAsync或bleDevice = await BluetoothLEDevice.FromBluetoothAddressAsync中重复使用它们。我上来了...
NVM 有效!