UWP串口初始化和验证 [英] UWP Serial Port Initialization and Verification

查看:64
本文介绍了UWP串口初始化和验证的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,

我正在尝试编写一个程序来检查串口是否可用且设备是否已连接。到目前为止,我正在尝试查看是否收到任何字节,并将其用作测试设备是否已连接。端口本身初始化
罚款,数据可以来回发送。 

I am trying to write a program that checks to see if a serial port is available and a device is connected to it. So far I am trying to see if there are any bytes received and use that as a test for whether or not a device is connected. The port itself initializes fine and data can be sent back and forth. 

问题:如果没有任何连接,下面发布的代码应始终失败。从main调用它时会失败,但是当它从GUI中的重新连接按钮调用时,它会在
失败时作为成功初始化返回。对于此问题,假设没有连接外部串行设备以返回响应。我正在使用内置UART的raspberry pi,即使没有连接到UART的设备也会初始化。 

The problem: The code posted below should always fail if there is nothing connected to it. It does fail when it is called from main, however when it is called from a reconnect button in the GUI it returns as a successful initialization when it should have failed. For this problem assume there is no external serial device connected to return a response. I am using the raspberry pi which has UART built in and will initialize even if there are no devices connected to the UART. 

发送的数据与此问题无关。如果没有返回串行响应,目标是返回失败的消息。

The data being sent is irrelevant to this problem. The goal is to return a failed message if there is no serial response returned.

我当前(不成功)的解决方案是使用task.whenAny()等待延迟和serialCommand并返回先完成的那个。我正在使用最新版本的visual studio。 

My current(unsuccessful) solution is to use the task.whenAny() to wait for a delay and the serialCommand and return the one that finishes first. I am using the latest version of visual studio. 

欢迎提供所有提示和改进。

All tips and improvements are welcome.

祝你好运,

Ben

public async void initializeSerial(byte[] inputCommandByteArray)
        {
            logNewEvent("Attempting to initialize Serial");
            //Creates two tasks to see which finishes first
            var timeoutTask = Task.Run(async () =>{
                await Task.Delay(TimeSpan.FromMilliseconds(1000));
            });

            var desiredTask = Task.Run(async () => {
                await SerialCommand(inputCommandByteArray, 1);
            }); 
            
            //Checks to see if the timeout finishes before the write
            Task finishedFirst = await Task.WhenAny(timeoutTask, desiredTask);

            //Checks if the timeout finished first.
            if (finishedFirst == timeoutTask)
            {
                logNewEvent("Serial initialization timed out. Initialization unsuccessful.");
            }
            else if(finishedFirst == desiredTask)
            {
                logNewEvent("Serial initialization successful!");
            }


        }
           
        /// <summary>
        /// Method takes two input parameters. The data to send and the expected return size.
        /// Method initializes the serial connection and then performes a serial write and a serial read.
        /// </summary>
        /// <param name="dataToSend"></param>
        /// <param name="expectedReturnSize"></param>
        public async Task SerialCommand(byte[] dataToSend, uint expectedReturnSize)
        {
            string aqs = SerialDevice.GetDeviceSelector("UART0");                   /* Find the selector string for the serial device   */
            var dis = await DeviceInformation.FindAllAsync(aqs);                    /* Find the serial device with our selector string  */
            SerialDevice SerialPort = await SerialDevice.FromIdAsync(dis[0].Id);    /* Create an serial device with our selected device */

            /* Configure serial settings */
            SerialPort.WriteTimeout = TimeSpan.FromMilliseconds(1000);
            SerialPort.ReadTimeout = TimeSpan.FromMilliseconds(1000);
            SerialPort.BaudRate = 9600;                                             /* mini UART: only standard baudrates */
            SerialPort.Parity = SerialParity.None;                                  /* mini UART: no parities             */
            SerialPort.StopBits = SerialStopBitCount.One;                           /* mini UART: 1 stop bit              */
            SerialPort.DataBits = 8;
            try
            {
                /* Write a string out over serial */
                DataWriter dataWriter = new DataWriter();
                dataWriter.WriteBytes(dataToSend);
                uint bytesWritten = await SerialPort.OutputStream.WriteAsync(dataWriter.DetachBuffer());

                /* Read data in from the serial port */
                DataReader dataReader = new DataReader(SerialPort.InputStream);
                uint bytesToRead = 0;
                bytesToRead = await dataReader.LoadAsync(expectedReturnSize);
                serialBytesReceived = new byte[bytesToRead];
                dataReader.ReadBytes(serialBytesReceived);
                logNewEvent("Number of bytes available to read: " + bytesToRead.ToString());
             

            }catch(Exception e)
            {
                 logNewEvent("Error: " + e.Message);
            }
            
        }

推荐答案

嗨glowblujel,

Hi glowblujel,

此论坛讨论并提出有关.NET Framework的问题基础课,因为您的问题与UWP更相关,我会将其移至UWP论坛以获得合适的支持。

This forum discuss and ask questions about .NET Framework Base Classes, since your issue is more related to UWP, I'll move it to UWP forum for suitable support.

感谢您的理解。

最好的问候,

张龙


这篇关于UWP串口初始化和验证的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆