在UWP中获取已知蓝牙设备的COM端口名称
问题描述:
我正在使用DeviceWatcher为UWP应用中的配对蓝牙设备获取DeviceInformation。我设置了DeviceWatcher像这样在UWP中获取已知蓝牙设备的COM端口名称
var requestedProperties = new string[] { "System.Devices.Aep.DeviceAddress", "System.Devices.Aep.IsConnected" };
var deviceWatcher = DeviceInformation.CreateWatcher("(System.Devices.Aep.ProtocolId:=\"{e0cbf06c-cd8b-4647-bb8a-263b43f0f974}\")", requestedProperties, DeviceInformationKind.AssociationEndpoint); // ClassGuid = {e0cbf06c-cd8b-4647-bb8a-263b43f0f974} includes all Bluetooth devices
deviceWatcher.Added += DeviceWatcher_Added;
deviceWatcher.Updated += DeviceWatcher_Updated;
deviceWatcher.Start();
当DeviceWatcher_Added事件处理程序被调用我检查,看看是否该设备是一个我是通过检查它的名字和它提供的服务RfcommServiceId.SerialPort.Uuid感兴趣的
一旦我有蓝牙设备的DeviceInformation,我有兴趣知道如何获取COM端口?我可以在设备管理器中看到它,它被列为“通过蓝牙链接的标准串口(COM8)”,但我看不到如何以编程方式在UWP中获得“COM8”。
我试图使DeviceInformation成SerialDevice,因此我可以再拿到SerialDevice.PortName(C.F. this答案),但我对SerialDevice.FromIdAsync(deviceInfo.Id)
调用失败了System.Exception的:数据无效。
(NB一些诱人的答案,像this和this,使用Windows管理Intrumentation WMI功能,但这些都无法在UWP)
答
在another questionRita建议要Serial UART sample这让我看到了一种做这个。我不会将此标记为一段时间的答案,因为它似乎太过间接而不能成为规范的方式。
虽然我的DeviceInformation为我的UWP应用中配对的蓝牙设备,但我也需要SerialDevice的列表,以便我可以匹配它们。这是最终的代码。
public async Task<string> ComPort(DeviceInformation deviceInfo)
{
var serialDevices = new Dictionary<string, SerialDevice>();
var serialSelector = SerialDevice.GetDeviceSelector();
var serialDeviceInformations = (await DeviceInformation.FindAllAsync(serialSelector)).ToList();
var hostNames = NetworkInformation.GetHostNames().Select(hostName => hostName.DisplayName.ToUpper()).ToList(); // So we can ignore inbuilt ports
foreach (var serialDeviceInformation in serialDeviceInformations)
{
if (hostNames.FirstOrDefault(hostName => hostName.StartsWith(serialDeviceInformation.Name.ToUpper())) == null)
{
try
{
var serialDevice = await SerialDevice.FromIdAsync(serialDeviceInformation.Id);
if (serialDevice != null)
{
serialDevices.Add(deviceInfo.Id, serialDevice);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.ToString());
}
}
}
// Example Bluetooth DeviceInfo.Id: "Bluetooth#Bluetooth9c:b6:d0:d6:d7:56-00:07:80:cb:56:6d"
// from device with Association Endpoint Address: "00:07:80:cb:56:6d"
var lengthOfTrailingAssociationEndpointAddresss = (2 * 6) + 5;
var bluetoothDeviceAddress = deviceInfo.Id.Substring(deviceInfo.Id.Length - lengthOfTrailingAssociationEndpointAddresss, lengthOfTrailingAssociationEndpointAddresss).Replace(":", "").ToUpper();
var matchingKey = serialDevices.Keys.FirstOrDefault(id => id.Contains(bluetoothDeviceAddress));
if (matchingKey != null)
{
return serialDevices[matchingKey].PortName;
}
return "";
}
你如何确保deviceInfo.Id是你的设备的ID(COM8)?你能否显示完整的代码使这个异常:'System.Exception:数据无效'? –
完整的代码是[这里](https://github.com/dumbledad/BluetoothCOMGleaner) – dumbledad
鉴于你已经知道'deviceInfo.Name',想知道你是否可以从这里获得'Id'? '(等待DeviceInformation.FindAllAsync(SerialDevice.GetDeviceSelector()))。Single(di => di.Name == deviceInfo.Name).Id' –