通过 Hololens 2 [Unity C#] 中的串口从蓝牙设备读取字符串

Read string from a bluetooth device through serial port in Hololens 2 [Unity C#]

我需要从通过蓝牙与 Hololens 2 配对的惯性传感器接收字符串。我能够在 HoloLens 的配置菜单中连接传感器,但在尝试使用串口接收数据时出现问题在 Unity 开发的应用程序中。

我已设法建立连接并使用 System.IO.Ports.SerialPort class (https://docs.microsoft.com/es-es/dotnet/api/system.io.ports.serialport?view=dotnet-plat-ext-5.0) in the Unity Editor. The problem comes when trying to stablish that same connection in the HoloLens, after some research I found out that System.IO.Ports.SerialPort class can´t be used in UWP apps, so I´m trying to use the Windows.Devices.SerialCommunication.SerialDevice class (https://docs.microsoft.com/en-us/uwp/api/windows.devices.serialcommunication.serialdevice?view=winrt-19041) 接收数据。这是一段应该建立连接的代码,我在脚本的 Awake 函数中使用它:

async void openConnection()
    {
#if !UNITY_EDITOR
        await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(
  Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
  {
      try
      {
                DeviceInformationCollection serialDeviceInfos = await DeviceInformation.FindAllAsync(SerialDevice.GetDeviceSelector());

                if (serialDeviceInfos != null){

                    foreach (DeviceInformation serialDeviceInfo in serialDeviceInfos){

                        SerialDevice serialDevice = await SerialDevice.FromIdAsync(serialDeviceInfo.Id);

                        if (serialDevice != null)
                        {
                            // Found a valid serial device.
                            // Reading a byte from the serial device.
                            DataReader dr = new DataReader(serialDevice.InputStream);
                            string drData = dr.ReadString(60);
                        
                            estadoSensor.text = drData;
                        }

                }   }
      }
      catch (Exception ex)
      {
          estadoSensor.text = ex.ToString();
          System.Diagnostics.Debug.WriteLine(ex);
      }
   });
#endif 
    }

当调用方法SerialDevice.FromIdAsync()时,即使serialDeviceInfo.Id不为null,该方法也会抛出一个System.Exception类型的异常,如果我没记错的话,它不能不要更通用。如您所见,我正在尝试在 UI 线程上调用该方法,因为我读过,否则它不会工作,但即使那样做,它对我也不起作用 (https://forum.unity.com/threads/hololens-device-permission-dialog-for-rfcomm-bluetooth-serial-port.513666/).

我也在Unity编辑器中为UWP构建后生成的package.appxmanifest文件中添加了这段代码,理论上它应该启用串行通信功能

    <DeviceCapability Name="serialcommunication">
        <Device Id="any">
            <Function Type="name:serialPort" />
        </Device>
    </DeviceCapability>

我希望我已经成功地解释了我的问题。

提前致谢!

Bluetooth SerialPort 无法在 HoloLens 2 上工作,因为 HoloLens 2 设备没有为传感器安装特定的驱动程序以通过连接的串行端口执行此操作。此外,建议您使用RFCOMM,更多信息请参见:https://docs.microsoft.com/en-us/windows/uwp/devices-sensors/send-or-receive-files-with-rfcomm