C#SerialPort-RS485如何在一个部分中接收所有数据

时间:2018-08-29 09:10:40

标签: c# serial-port rs485

我有一台通过RS485通信的设备,我需要在C#中进行回送,以接收我的数据并将其发送回去。第一个字节包含有关即将到来的数据长度的信息。有时,C#会在多个部分触发事件。我只需要一部分就可以收到它们,这样我就可以一次性寄回。

var buffer = new byte[1000];
port = new SerialPort(ConfigParams.PORT, 115200, Parity.None, 8, StopBits.One);                
port.Handshake = Handshake.None;
port.RtsEnable = true;
port.DtrEnable = true;                
port.DataReceived += (sender, e) =>
{  
  var length = port.ReadByte();                    
  Thread.Sleep(10);
  var bytes = port.Read(buffer, 1, length);
  buffer[0] = (byte)length;
  port.Write(buffer, 0, length + 1);
  mainForm.Log("Port (" + (length + 1).ToString() +"): " + Encoding.UTF8.GetString(buffer, 0, length + 1)+"\n");
  mainForm.Log("Data was sended.\n");                    
};

第一步,我读取第一个字节以获取即将到来的字节数。然后,我读取其余字节。如果我未在其中插入Thread.Sleep(10)行,则有时会在多个部分触发Event DataReceived。有了Thread.Sleep(10),它每次都能正常工作。

您知道为什么会这样吗?我希望如果我说我想读取40个字节,SerialPort将尝试接收所有这40个字节或发生异常。我试图更改属性ReadTimeout,但没有更改。

1 个答案:

答案 0 :(得分:1)

这里的问题是,当您调用SerialPort.Read()时,它将等待缓冲区中的至少一个字节,然后它将返回其具有的所有字节,直到指定长度的最大值。

这意味着它可能返回的金额少于要求的金额。

要避免此问题,您可以编写与此类似的代码(重要的一点在private blockingRead()方法中):

/// <summary>
/// Attempts to read <paramref name="count"/> bytes into <paramref name="buffer"/> starting at offset <paramref name="offset"/>.
/// If any individual port read times out, a <see cref="TimeoutException"/> will be thrown.
/// </summary>
/// <param name="buffer">The byte array to write the input to. </param>
/// <param name="offset">The offset in buffer at which to write the bytes. </param>
/// <param name="count">The number of bytes to read from the port.</param>
/// <param name="timeoutMilliseconds">
/// The timeout for each individual port read (several port reads may be issued to fulfil the total number of bytes required).
/// If this is -2 (the default) the current <see cref="ReadTimeout"/> value is used.
/// If this is -1 or <see cref="SerialPort.InfiniteTimeout"/>, an infinite timeout is used.
/// </param>
/// <exception cref="TimeoutException">Thrown if any individual port read times out.</exception>

public void BlockingRead(byte[] buffer, int offset, int count, int timeoutMilliseconds = SerialComPortTimeout.UseDefault)
{
    if (timeoutMilliseconds < SerialComPortTimeout.UseDefault)
        throw new ArgumentOutOfRangeException(nameof(timeoutMilliseconds),timeoutMilliseconds, $"{nameof(timeoutMilliseconds)} cannot be less than {SerialComPortTimeout.UseDefault}." );

    int timeoutToRestore = setTimeoutAndReturnOriginal(timeoutMilliseconds);

    try
    {
        blockingRead(buffer, offset, count);
    }

    finally
    {
        if (timeoutToRestore != SerialComPortTimeout.UseDefault)
            this.ReadTimeout = timeoutToRestore;
    }
}

private void blockingRead(byte[] buffer, int offset, int count)
{
    while (count > 0)
    {
        // SerialPort.Read() blocks until at least one byte has been read, or SerialPort.ReadTimeout milliseconds
        // have elapsed. If a timeout occurs a TimeoutException will be thrown.
        // Because SerialPort.Read() blocks until some data is available this is not a busy loop,
        // and we do NOT need to issue any calls to Thread.Sleep().

        int bytesRead = _serialPort.Read(buffer, offset, count);
        offset += bytesRead;
        count -= bytesRead;
    }
}

private int setTimeoutAndReturnOriginal(int timeoutMilliseconds)
{
    int originalTimeout = this.ReadTimeout;

    if ((timeoutMilliseconds != SerialComPortTimeout.UseDefault) && (originalTimeout != timeoutMilliseconds))
    {
        this.ReadTimeout = timeoutMilliseconds;
        return originalTimeout;
    }

    return SerialComPortTimeout.UseDefault;
}

请注意,SerialPort的.Net实现是易变的-有关详细信息,请参见this article