简体   繁体   English

.NET SerialPort写入/读取优化

[英].NET SerialPort Write/Read optimization

I've an UART device which I'm writing to it a command (via System.IO.Ports.SerialPort) and then immediately the device will respond. 我有一个UART设备,正在向它写入命令(通过System.IO.Ports.SerialPort),然后该设备将立即响应。

So basically my approach is: 所以基本上我的方法是:

->Write to SerialPort->await Task.Delay->Read from the Port. ->写入串行端口->等待Task.Delay->从端口读取。

//The port is open all the time.
public async byte[] WriteAndRead(byte[] message){ 
port.Write(command, 0, command.Length);
await Task.Delay(timeout);
var msglen = port.BytesToRead;
    if (msglen > 0)
                {

                    byte[] message = new byte[msglen];
                    int readbytes = 0;

                    while (port.Read(message, readbytes, msglen - readbytes) <= 0)
                        ;

                    return message;

                    }

This works fine on my computer. 这在我的计算机上工作正常。 But if I try it on another computer for example, the bytesToRead property is sometimes mismatched. 但是,例如,如果我在另一台计算机上尝试使用,则bytesToRead属性有时会不匹配。 There are empty bytes in it or the answer is not completed. 其中有空字节或答案未完成。 (Eg I get two bytes, if I expect one byte: 0xBB, 0x00 or 0x00, 0xBB) (例如,如果我希望一个字节,则得到两个字节:0xBB,0x00或0x00、0xBB)

I've also looked into the SerialPort.DataReceived Event, but it fires too often and is (as far as I understand) not really useful for this write and read approach. 我也研究了SerialPort.DataReceived事件,但是它触发的频率太高,并且(据我所知)对于这种读写方法实际上没有用。 (As I expect the answer immediately from the device). (因为我期望设备立即提供答案)。

Is there a better approach to a write-and-read? 是否有更好的读写方式?

Read carefully the Remarks in https://msdn.microsoft.com/en-us/library/ms143549(v=vs.110).aspx You should not rely on the BytesToRead value to indicate message length. 仔细阅读https://msdn.microsoft.com/zh-cn/library/ms143549(v=vs.110).aspx中的备注。您不应依赖BytesToRead值来指示消息长度。 You should know, how much data you expect to read to decompose the message. 您应该知道,希望读取多少数据才能分解消息。 Also, as @itsme85 noticed, you are not updating the readbytes, and therefore you are always writing received bytes to beginning of your array. 另外,正如@ itsme85所注意到的,您没有更新readbytes,因此,您总是将接收到的字节写到数组的开头。 Proper code with updating the readbytes should look like this: 更新readbytes的正确代码应如下所示:

int r;
while ((r = port.Read(message, readbytes, msglen - readbytes)) <= 0){
  readbytes += r;
}

However, during the time you will read data, more data can come and your "message" might be incomplete. 但是,在您读取数据期间,可能会收到更多数据,并且您的“消息”可能不完整。 Rethink, what you want to achieve. 重新思考,您想要实现的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM