gpt4 book ai didi

c# - 从 rfcomm 设备服务中检索蓝牙设备的名称

转载 作者:太空宇宙 更新时间:2023-11-03 12:35:39 33 4
gpt4 key购买 nike

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

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

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

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

我发现我可以使用上面代码返回的设备 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() 函数。这行得通,但我想知道是否有更清晰的解决方案来解决我的问题,因为如果字符串格式发生变化,解析字符串可能是一个真正的问题。

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

最佳答案

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

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 通常表示通过无线或网络协议(protocol)发现的设备。 AssociationEndpoint 对象是单个 AssociationEndpointContainer 对象的子对象,可以包含 0 个或多个 AssociationEndpointService 对象。而RFComm服务是蓝牙设备包含的一个AssociationEndpointService。更多信息,请参阅DeviceInformationKind enumerationEnumerate devices over a network .

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

关于c# - 从 rfcomm 设备服务中检索蓝牙设备的名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41152410/

33 4 0
文章推荐: php - 使用 mySQL 和 PHP 填充