[英]Paired(Bonded) device Reconnection/Notification - UWP
客户:电脑
服务器:手机
>>>手机广告无时无刻不在<<<
在 PC(UWP) 应用程序上,用户选择要与之配对的手机
配对后,PC 使用await BluetoothLEDevice.FromIdAsync
获得蓝牙 LE object
PC 使用await desiredBluetoothLeDevice.GetGattServicesForUuidAsync
搜索服务
PC 使用await customService.GetCharacteristicsForUuidAsync
搜索特征
PC 使用await customCharacteristic.GetDescriptorsAsync
搜索描述符
PC 使用await customCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync (GattClientCharacteristicConfigurationDescriptorValue.Notify)
订阅通知
PC 使用await customCharacteristic.WriteValueAsync
写入消息
在通过通知接收消息后,PC 使用await customCharacteristic.WriteClientCharacteristicConfigurationDescriptorAsync (GattClientCharacteristicConfigurationDescriptorValue.None)
取消订阅通知
断开
private void Disconnect()
{
customCharacteristic?.Service?.Dispose();
customCharacteristic = null;
customService?.Dispose();
customService = null;
desiredBluetoothLeDevice?.Dispose();
desiredBluetoothLeDevice = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}
private async void Reconnect()
{
reconnBluetoothLeDevice = await BluetoothLEDevice.FromIdAsync(ID_of_BleDevice_I_saved);
newSession = await GattSession.FromDeviceIdAsync(reconnBluetoothLeDevice.BluetoothDeviceId);
newSession.MaintainConnection = true;
reconnBluetoothLeDevice.ConnectionStatusChanged += ConnectionStatusChangedHandler;
}
private async void ConnectionStatusChangedHandler(BluetoothLEDevice reconnBluetoothLeDevice, object o)
{
if(reconnBluetoothLeDevice.ConnectionStatus.ToString() == "Conncected")
{
sList = reconnBluetoothLeDevice.GetGattServicesForUuidAsync(custom_service_GUID)
.
.
.
}
}
PC重复步骤 4-8
断开
private void DisconnectAfterReconnection()
{
customCharacteristic?.Service?.Dispose();
customCharacteristic = null;
customService?.Dispose();
customService = null;
reconBluetoothLeDevice.ConnectionStatusChanged -= ConnectionStatusChangedHandler;
reconnBluetoothLeDevice?.Dispose();
reconnBluetoothLeDevice = null;
newSession.MaintainConnection = false;
newSession.Dispose();
newSession = null;
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
使用ConnectionStatus
和IsConnected
属性,我发现奇怪的行为:
有时设备在第 10 步之前已连接(手动重新连接)
有时设备在重新连接后立即断开连接并再次连接(即 ConnectionStatusChangedHandler 获取事件 3 次)
我听说当设备配对(绑定)并订阅通知时,它们会自动重新连接。
对该论坛的回答说客户端需要重新启用通知。
我正在做的正确方法是重新连接???
我是否需要跳过第 8 步进行自动重新连接?
自动重新连接实际上是如何工作的? 我可以跳过第 10 步吗?
我很混乱...
在这里,如果您需要,我也发布了移动(Android)端。 (我没有提到阅读特征部分,步骤1和2,因为这不是这里的问题)
感谢您阅读这个长长的问题。 我将不胜感激任何帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.