【问题标题】:serial connection on UWP Headless appUWP Headless 应用上的串行连接
【发布时间】:2016-12-05 08:25:08
【问题描述】:

我想为 Raspberry Pi 创建一个涉及从串行端口读取数据的无头应用程序。

Microsoft 的示例应用运行良好,只是它有一个用户界面。

在创建无头应用程序时,我将所有相关部分接管如下:

var aqs = SerialDevice.GetDeviceSelector();

var dis = await DeviceInformation.FindAllAsync(aqs);

foreach (var t in dis)
{
    if (t.Id.Contains("FTDI"))
    {
        listOfDevices.Add(t);

    }

}

if (listOfDevices.Count == 1)
{
    DeviceInformation entry = listOfDevices[0];

    try
    {
        serialPort = await SerialDevice.FromIdAsync(entry.Id);
        serialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
        serialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
        serialPort.BaudRate = 9600;
        serialPort.Parity = SerialParity.None;
        serialPort.StopBits = SerialStopBitCount.One;
        serialPort.DataBits = 8;
        serialPort.Handshake = SerialHandshake.None;

        ...

有一根 USB-FTDI-cable,其中 ID 包含“FTDI”如下:

serialPort = await SerialDevice.FromIdAsync(entry.Id);

程序在程序实例消失并忽略我的断点之前到达这一行。

有什么想法吗?

【问题讨论】:

    标签: c# xamarin uwp iot headless


    【解决方案1】:

    我使用您的代码并在 Package.appxmanifest 中添加以下行。

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

    它对我有用。

    更新:

    根据你的项目(你发给我的),因为你的 ListAvailablePorts() 是一个异步操作,你需要use the GetDeferral method to get a background task deferral to keep the host process from being suspended or terminated before the asynchronous operation complete。您可以像这样编辑您的代码:

        BackgroundTaskDeferral _deferral = null;
        public async void Run(IBackgroundTaskInstance taskInstance)
        {
            _deferral = taskInstance.GetDeferral();
            // 
            // TODO: Insert code to start one or more asynchronous methods 
            //
            try
            {
                //var u = new USART();
                //await u.Initialize(115200, SerialParity.None, SerialStopBitCount.One, 8);
                listOfDevices = new ObservableCollection<DeviceInformation>();
                ListAvailablePorts();
            }
    
            ...
        }
    

    并在异步操作完成后调用_deferral.Complete()

    【讨论】:

    • 嗨丽塔,我已经有了设备功能:设备> 但没有结果。
    • 我怎样才能把它寄给你?
    • @Axel 您可以编辑您的问题并将代码粘贴到其中。
    • 丽塔,想把项目发给你……使用系统;使用 System.Collections.ObjectModel;使用 System.Globalization;使用 System.Threading;使用 System.Threading.Tasks;使用 Windows.ApplicationModel.Background;使用 Windows.Devices.Enumeration; .. 现在只剩下 320 个字符了 :) 不是有类似私信的东西吗?
    • @Axel 我测试了你的项目并更新了我的答案。请检查一下。如果有任何问题,请随时告诉我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-27
    • 1970-01-01
    • 1970-01-01
    • 2016-07-28
    • 2018-04-01
    • 1970-01-01
    相关资源
    最近更新 更多