首页 > 解决方案 > 如何重新连接到 BLE 设备?- UWP

问题描述

设备 id 和地址都是随机的,我不能将它们重新用于bleDevice = await BluetoothLEDevice.FromIdAsyncor bleDevice = await BluetoothLEDevice.FromBluetoothAddressAsync

我想出了 2 个可能的解决方案:(1)ConnectionStatusChange 和(2)配对,

但两种情况我都有问题。


(1)主要问题

在断开连接之前,我先将文件另存bleDevicebleDeviceReconnect.

然后我取消订阅,处理特性&服务&蓝牙文件,并将它们设置为空。

在重新连接的情况下,而不是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 或地址不变?

我首先需要使用我上面所说的任何一种方法来获取蓝牙 LE 对象,我可以使用它来查找自定义服务 ( sList = bleDevice.GetGattServicesForUuidAsync) 和特性 ( cList = sList.Services[0].GetCharacteristicsForUuidAsync),并订阅/写入特性等。

因此,如果 id 或地址发生变化,配对就没有任何意义。


如何正确重新连接到 BLE 设备???

我真的很感激任何帮助。


编辑

Richard Zhang - MSFT 要求我添加一个最小的可运行演示:

微软蓝牙LE代码

(1) Scenario2_Client.xaml

添加 2 个按钮:[断开连接] 和 [重新连接]

*断开连接不会立即发生。请等待至少 5 秒,然后再按 [重新连接]

(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 帐户,上传我的项目,然后将链接复制并粘贴到此处。

标签: uwpbluetooth-lowenergywin-universal-appwindows-10-universalgatt

解决方案


NVM有效!

移动应用程序是配对期间的问题。

此外,我必须配对并添加处理程序才能使其工作。

我可以通过处理程序获取 BluetoothLEDevice 对象,但搜索服务现在是个问题。

由于这与我在这篇文章中提出的问题不同,我将发布一个新问题。


推荐阅读