【问题标题】:Retrieve name of bluetooth device from rfcomm device services从 rfcomm 设备服务中检索蓝牙设备的名称
【发布时间】:2017-04-30 08:41:39
【问题描述】:

上下文如下,我们有多辆包含蓝牙转串口设备的卡车,我们为每辆卡车的蓝牙指定了一个唯一的名称,以便能够连接到特定的卡车。

我使用此代码检索所有 RFComm 服务:

DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort))

问题是返回的所有 DeviceInformation 对象在 Name 属性中都包含 RFComm 服务的名称,而不是蓝牙设备名称。当我的项目是一个 Win 8 商店应用程序时,一切都很好,因为 name 属性包含蓝牙设备名称。

我发现我可以使用上述代码返回的设备 ID 创建一个 BluetoothDevice 对象,但随后应用程序要求对所有设备使用蓝牙设备,直到我找到合适的设备。我想防止这种情况发生,因为 Win 8 商店应用程序并非如此。

我找到的第二个解决方案是解析 RFComm 服务的设备 ID,看起来像这样

Bluetooth#Bluetooth00:c2:c6:56:b0:61-00:15:be:0f:02:d7#RFCOMM:00000000:{00001101-0000-1000-8000-00805f9b34fb}

删除“#RFCOMM”之后的所有内容并使用DeviceInformation.CreateFromIdAsync() 函数。这可行,但我想知道是否有更简洁的解决方案来解决我的问题,因为如果字符串格式发生变化,解析字符串可能是一个真正的问题。

有没有一种方法可以检索蓝牙设备的名称,而无需要求使用所有蓝牙设备,直到我们找到它?

【问题讨论】:

  • 是的,它有效,我将您的答案标记为已接受。谢谢

标签: c# bluetooth uwp windows-10 rfcomm


【解决方案1】:

您可以尝试使用以下代码获取蓝牙设备的名称:

var serviceInfoCollection = await DeviceInformation.FindAllAsync(RfcommDeviceService.GetDeviceSelector(RfcommServiceId.SerialPort), new string[] { "System.Devices.AepService.AepId" });

foreach (var serviceInfo in serviceInfoCollection)
{
    var deviceInfo = await DeviceInformation.CreateFromIdAsync((string)serviceInfo.Properties["System.Devices.AepService.AepId"]);

    System.Diagnostics.Debug.WriteLine($"Device name is: '{deviceInfo.Name}' and Id is: '{deviceInfo.Id}'");
}

这里的重点是蓝牙设备是一种AssociationEndpoint对象。 AEP 通常代表通过无线或网络协议发现的设备。 AssociationEndpoint 对象是单个 AssociationEndpointContainer 对象的子对象,可以包含 0 个或多个 AssociationEndpointService 对象。而RFComm service是蓝牙设备所包含的AssociationEndpointService之一。有关详细信息,请参阅 DeviceInformationKind enumerationEnumerate devices over a network

AssociationEndpointService 有几个属性。其中之一是 System.Devices.AepService.AepId,它表示父 AssociationEndpoint 对象的标识符。所以我们可以使用这个属性来获取蓝牙设备信息,一旦我们得到设备信息,我们就可以很容易的得到设备名称。但是 System.Devices.AepService.AepId 属性不是DeviceInformation 中的常用属性。所以我们需要使用DeviceInformation.FindAllAsync(String, IIterable(String)) 方法来要求这个额外的属性。更多信息请见Device information properties

【讨论】:

  • 关于蓝牙结构的很好解释的答案谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-07-02
  • 2015-01-23
  • 2016-07-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多