UWP 蓝牙 RfcommDeviceService.FromIdAsync 为空

UWP Bluetooth RfcommDeviceService.FromIdAsync is null

我正在尝试使用以下代码连接到带有 UWP 的设备:

var devices = await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Disconnected));
var device = devices.FirstOrDefault()
if (device != null && device.Name == "MyDevice")
{
    var rfcommService = await RfcommDeviceService.FromIdAsync(device.Id);
    var socket = new StreamSocket();
    await _socket.ConnectAsync(rfDeviceService.ConnectionHostName, rfDeviceService.ConnectionServiceName);
}

我设法找到了我的设备,其中包含所有信息。

RfcommDeviceService.FromIdAsync(device.Id) 总是 returns null,因为它 returns null 太快了,感觉它事件不能 "connect" 或接收信息。

我的包 ApplicationManifest 有以下与此相关的实体:

<Capabilities>
<Capability Name="internetClient" />
<DeviceCapability Name="bluetooth" />
<DeviceCapability Name="bluetooth.rfcomm">
  <Device Id="any">
    <Function Type="name:serialPort" />
  </Device>
</DeviceCapability>
<DeviceCapability Name="serialcommunication">
  <Device Id="any">
    <Function Type="name:serialPort" />
  </Device>
</DeviceCapability>

有人成功连接到蓝牙设备吗?

从昨天开始就一直在寻找答案,在我 post 10 分钟后我找到了一个带有答案的例子。我只是 post 在这里,以便其他人将来会发现:

var devices = await DeviceInformation.FindAllAsync(BluetoothDevice.GetDeviceSelectorFromConnectionStatus(BluetoothConnectionStatus.Disconnected));
var device = devices.FirstOrDefault()
if (device != null && device.Name == "MyDevice")
{
    var bluetoothDevice = await BluetoothDevice.FromIdAsync(device.Id);
    var rfcommServices = await bluetoothDevice.GetRfcommServicesForIdAsync(RfcommServiceId.FromUuid(RfcommServiceId.SerialPort.Uuid), BluetoothCacheMode.Uncached);
    if (rfcommServices.Services.Count > 0)
    {
        var service = rfcommServices.Services[0];
        await _socket.ConnectAsync(service.ConnectionHostName, service.ConnectionServiceName);
    }
}

绝对可以编写更漂亮的代码,只是展示如何让它工作:)