隔离 Modbus RTU 超时请求的迟到应答

This commit is contained in:
wanglei 2026-12-05 20:28:47 +08:00
parent 4a96aa38e2
commit 8d3114efa1
4 changed files with 286 additions and 70 deletions

View File

@ -1,6 +1,5 @@
using System.IO;
using System.Net;
using System.Threading;
namespace PLCSharp.VVMs.Connects.ModbusRtu
{
@ -28,41 +27,67 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
private System.IO.Ports.SerialPort _port;
private RtuSession _session;
public ModbusRtuClient() { }
internal ModbusRtuClient(RtuSession session)
{
_session = session;
Connected = true;
}
/// <summary>打开串口</summary>
public override void Open()
{
try
lock (_lock)
{
_port?.Close();
_port = new System.IO.Ports.SerialPort(IP_SerialPort, Params.BaudRate, Params.ParityValue, Params.DataBits, Params.StopBitsValue)
ClosePort();
try
{
ReadTimeout = 5000,
WriteTimeout = 2000
};
_port.Open();
Connected = true;
Log($"串口 {IP_SerialPort} 已打开");
_port = new System.IO.Ports.SerialPort(IP_SerialPort, Params.BaudRate, Params.ParityValue, Params.DataBits, Params.StopBitsValue)
{
ReadTimeout = 5000,
WriteTimeout = 2000
};
_port.Open();
var port = _port;
double stopBits = port.StopBits == System.IO.Ports.StopBits.OnePointFive ? 1.5 :
port.StopBits == System.IO.Ports.StopBits.Two ? 2 : 1;
double bits = 1 + port.DataBits + stopBits + (port.Parity == System.IO.Ports.Parity.None ? 0 : 1);
int gapMs = port.BaudRate > 19200 ? 2 : (int)Math.Ceiling(3500 * bits / port.BaudRate);
_session = new RtuSession(port.BaseStream, () => port.BytesToRead, port.DiscardInBuffer, gapMs);
Connected = true;
Log($"串口 {IP_SerialPort} 已打开");
}
catch (Exception ex)
{
ClosePort();
Log($"打开串口失败: {ex.Message}");
}
}
catch (Exception ex)
}
public override void Close()
{
lock (_lock) ClosePort();
}
private void ClosePort()
{
_session = null;
try { _port?.Dispose(); }
catch (Exception ex) { Log($"关闭串口失败: {ex.Message}"); }
finally
{
Log($"打开串口失败: {ex.Message}");
_port = null;
Connected = false;
}
}
/// <summary>
/// 关闭
/// </summary>
public override void Close()
{
try { _port?.Close(); } catch { }
_port = null;
Connected = false;
}
// ─── CRC16-Modbus ───
private static ushort CalcCrc(byte[] data, int offset, int count)
internal static ushort CalcCrc(byte[] data, int offset, int count)
{
ushort crc = 0xFFFF;
for (int i = 0; i < count; i++)
@ -95,36 +120,13 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
// ─── 读写串口 ───
// 保留响应的线上布局供 CRC 校验及 ReceiveData 使用。
internal static byte[] ReadResponse(Stream stream, byte unitId, byte functionCode, ReadOnlySpan<byte> requestData)
{
byte[] head = new byte[2];
stream.ReadExactly(head);
if (head[0] != unitId || (head[1] != functionCode && head[1] != (functionCode | 0x80)))
throw new InvalidDataException("ModbusRTU 应答站号或功能码与请求不匹配");
bool isError = (head[1] & 0x80) != 0;
bool hasByteCount = functionCode == FC_READ_HOLDING_REGISTERS && !isError;
int count = hasByteCount ? stream.ReadByte() : isError ? 1 : 4;
if (count < 0) throw new EndOfStreamException();
byte[] data = new byte[count];
stream.ReadExactly(data);
byte[] response = hasByteCount ? [.. head, (byte)count, .. data] : [.. head, .. data];
Span<byte> crc = stackalloc byte[2];
stream.ReadExactly(crc);
if (CalcCrc(response, 0, response.Length) != (crc[0] | crc[1] << 8))
throw new InvalidDataException("ModbusRTU: CRC 校验失败");
ModbusResponse.ValidatePdu(functionCode, requestData, response.AsSpan(1));
return response;
}
private byte[] Execute(byte unitId, byte functionCode, byte[] requestData)
{
lock (_lock)
{
Successful = false;
ReceiveData = null;
if (_port == null || !_port.IsOpen)
if (_session == null)
{
Log("ModbusRTU: 串口未打开");
return null;
@ -132,20 +134,9 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
try
{
// 清空接收缓冲区,避免残留数据污染本次读取
_port.DiscardInBuffer();
byte[] request = BuildRequest(unitId, functionCode, requestData);
_port.Write(request, 0, request.Length);
Log($"ModbusTx [{BitConverter.ToString(request).Replace("-", " ")}]");
// 等待响应:按波特率计算 3.5 字符时间 + 50ms 从机处理余量
double charMs = 1000.0 / Params.BaudRate * 10; // 8N1 = 10 bits/char
int waitMs = (int)Math.Ceiling(3.5 * charMs) + 50;
if (waitMs < 20) waitMs = 20;
Thread.Sleep(waitMs);
byte[] response = ReadResponse(_port.BaseStream, unitId, functionCode, requestData);
byte[] response = _session.Exchange(request, Log);
if (response == null) return null;
Log($"ModbusRx [{BitConverter.ToString(response).Replace("-", " ")}]");
if ((response[1] & 0x80) != 0)
{
@ -164,21 +155,19 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
}
catch (TimeoutException)
{
Log("ModbusRTU: 读取超时");
_port?.DiscardInBuffer();
Log("ModbusRTU: 收发超时,等待丢弃迟到应答;若从站无应答,请确认从站及串口线路空闲后重新打开串口");
return null;
}
catch (IOException)
catch (IOException ex)
{
Log("ModbusRTU: IO 错误");
_port?.DiscardInBuffer();
Log($"ModbusRTU: IO 错误: {ex.Message}");
ClosePort();
return null;
}
catch (Exception ex)
{
Log($"ModbusRTU 异常: {ex.Message}");
_port?.DiscardInBuffer();
Connected = false;
ClosePort();
return null;
}
}

View File

@ -0,0 +1,87 @@
using System.IO;
using System.Threading;
namespace PLCSharp.VVMs.Connects.ModbusRtu;
internal sealed class RtuSession(Stream stream, Func<int> bytesAvailable, Action discardInput, int frameGapMs)
{
// Execute、Open 和 Close 由客户端的同一把锁串行化。
private RtuResponseReader _lateReply;
internal byte[] Exchange(byte[] request, Action<string> log)
{
if (_lateReply != null)
{
// 轮询只消费目前可读的字节;从站一直不应答时不阻塞其他串口的轮询。
try
{
if (_lateReply.Read(stream, bytesAvailable()) == null) return null;
}
catch (InvalidDataException ex)
{
throw new IOException("迟到帧无法与超时请求匹配,请确认从站已空闲后重新打开串口", ex);
}
_lateReply = null;
log("ModbusRTU: 已丢弃上一笔请求的迟到应答");
Thread.Sleep(frameGapMs);
}
discardInput();
var reply = new RtuResponseReader(request[0], request[1], request[2..^2]);
try
{
stream.Write(request);
log($"ModbusTx [{BitConverter.ToString(request).Replace("-", " ")}]");
Thread.Sleep(frameGapMs + 50);
return reply.Read(stream, int.MaxValue);
}
catch (TimeoutException)
{
// 写超时也可能已经送达从站;此处不重发命令。
_lateReply = reply;
throw;
}
}
}
// TimeoutException 可能发生在帧内任何位置。每次底层 Read 成功就保存进度。
internal sealed class RtuResponseReader(byte unitId, byte functionCode, byte[] requestData)
{
private readonly byte[] _frame = new byte[256];
private int _received;
internal byte[] Read(Stream stream, int budget)
{
if (!ReadUntil(stream, 2, ref budget)) return null;
bool isError = _frame[1] == (functionCode | 0x80);
if (_frame[0] != unitId || (_frame[1] != functionCode && !isError))
throw new InvalidDataException("ModbusRTU 应答站号或功能码与请求不匹配");
int length = isError ? 5 : 8;
if (!isError && functionCode == ModbusRtuClient.FC_READ_HOLDING_REGISTERS)
{
if (!ReadUntil(stream, 3, ref budget)) return null;
length = 5 + _frame[2];
if (length > _frame.Length) throw new InvalidDataException("ModbusRTU 应答过长");
}
if (!ReadUntil(stream, length, ref budget)) return null;
int end = length - 2;
if (ModbusRtuClient.CalcCrc(_frame, 0, end) != (_frame[end] | _frame[end + 1] << 8))
throw new InvalidDataException("ModbusRTU: CRC 校验失败");
ModbusResponse.ValidatePdu(functionCode, requestData, _frame.AsSpan(1, end - 1));
return _frame[..end];
}
private bool ReadUntil(Stream stream, int end, ref int budget)
{
while (_received < end && budget > 0)
{
int n = stream.Read(_frame, _received, Math.Min(end - _received, budget));
if (n == 0) throw new EndOfStreamException();
_received += n;
budget -= n;
}
return _received >= end;
}
}

View File

@ -13,7 +13,7 @@ public class ModbusRtuFramingTests
public void ValidResponseKeepsWireLayout(byte function, string request, string wire, string expected)
{
using var stream = new MemoryStream(Convert.FromHexString(wire));
Assert.Equal(Convert.FromHexString(expected), ModbusRtuClient.ReadResponse(stream, 17, function, Convert.FromHexString(request)));
Assert.Equal(Convert.FromHexString(expected), new RtuResponseReader(17, function, Convert.FromHexString(request)).Read(stream, int.MaxValue));
Assert.Equal(stream.Length, stream.Position);
}
@ -21,7 +21,7 @@ public class ModbusRtuFramingTests
public void BadWriteResponseCrcIsRejected()
{
using var stream = new MemoryStream(Convert.FromHexString("1106000100030000"));
Assert.Throws<InvalidDataException>(() => ModbusRtuClient.ReadResponse(stream, 17, 6, [0, 1, 0, 3]));
Assert.Throws<InvalidDataException>(() => new RtuResponseReader(17, 6, [0, 1, 0, 3]).Read(stream, int.MaxValue));
}
[Theory]
[InlineData(6, "00010003", "1206000100039AA8")]
@ -37,7 +37,7 @@ public class ModbusRtuFramingTests
{
using var stream = new MemoryStream(Convert.FromHexString(wire));
Assert.Throws<InvalidDataException>(() =>
ModbusRtuClient.ReadResponse(stream, 17, function, Convert.FromHexString(request)));
new RtuResponseReader(17, function, Convert.FromHexString(request)).Read(stream, int.MaxValue));
}
[Fact]

View File

@ -0,0 +1,140 @@
using System.IO;
using PLCSharp.VVMs.Connects.ModbusRtu;
namespace PLCSharp.Tests;
public class ModbusRtuTimeoutTests
{
// 17 号站,读两个寄存器。两笔请求的起始地址不同,应答仅由寄存器值区分。
private static readonly byte[] Old = Convert.FromHexString("110304000A01024BA1");
private static readonly byte[] Fresh = Convert.FromHexString("110304002A01038BAB");
[Theory]
[InlineData(0)]
[InlineData(1)]
[InlineData(2)]
[InlineData(3)]
[InlineData(5)]
[InlineData(8)]
public void LateReadNeverCompletesTheNextRequest(int receivedBeforeTimeout)
{
using var wire = new ScriptedPort();
bool oldDelivered = false;
wire.OnWrite = number => wire.Receive(number == 1 ? Old[..receivedBeforeTimeout]
: oldDelivered ? Fresh : Old[receivedBeforeTimeout..]);
var client = wire.Client;
Assert.Null(client.ReadHoldingRegisters(1, 2, 17));
Assert.Null(client.ReadHoldingRegisters(20, 2, 17));
Assert.False(client.Successful);
Assert.Null(client.ReceiveData);
Assert.Single(wire.Writes);
// 分两次收到余下字节;只收到前半截时也不能发送新请求。
wire.Receive(Old[receivedBeforeTimeout..^1]);
Assert.Null(client.ReadHoldingRegisters(20, 2, 17));
Assert.Single(wire.Writes);
wire.Receive(Old[^1..]);
oldDelivered = true;
Assert.Equal(new ushort[] { 42, 259 }, client.ReadHoldingRegisters(20, 2, 17));
Assert.Equal(2, wire.Writes.Count);
Assert.Equal((byte)20, wire.Writes[1][3]);
Assert.True(client.Successful);
Assert.Equal(Fresh[..^2], client.ReceiveData);
}
[Fact]
public void PendingWriteIsNeverRetransmittedAndItsEchoIsDiscarded()
{
using var wire = new ScriptedPort();
var client = wire.Client;
Assert.False(client.WriteSingleRegister(1, 3, 17));
Assert.False(client.WriteSingleRegister(1, 3, 17));
Assert.Single(wire.Writes);
wire.Receive(wire.Writes[0]); // 迟到的合法单写回显
wire.OnWrite = _ => wire.Receive(Fresh);
Assert.Equal(new ushort[] { 42, 259 }, client.ReadHoldingRegisters(20, 2, 17));
Assert.Equal(new byte[] { 6, 3 }, wire.Writes.Select(frame => frame[1]));
}
[Fact]
public void LateDeviceExceptionEndsOnlyTheTimedOutRequest()
{
using var wire = new ScriptedPort();
var client = wire.Client;
Assert.False(client.WriteSingleRegister(1, 3, 17));
wire.Receive(Convert.FromHexString("118602C264"));
wire.OnWrite = _ => wire.Receive(Fresh);
Assert.Equal(new ushort[] { 42, 259 }, client.ReadHoldingRegisters(20, 2, 17));
Assert.Equal(2, wire.Writes.Count);
}
[Fact]
public void CorruptLateFrameCannotReleaseTheNextWrite()
{
using var wire = new ScriptedPort();
var client = wire.Client;
Assert.Null(client.ReadHoldingRegisters(1, 2, 17));
byte[] corrupt = [.. Old];
corrupt[^1] ^= 1;
wire.Receive(corrupt);
Assert.False(client.WriteSingleRegister(1, 3, 17));
Assert.False(client.Connected);
Assert.False(client.Successful);
Assert.Null(client.ReceiveData);
Assert.Single(wire.Writes);
}
[Fact]
public void WriteTimeoutAfterTransmissionLeavesOneOutstandingRequest()
{
using var wire = new ScriptedPort();
wire.OnWrite = _ => throw new TimeoutException();
Assert.False(wire.Client.WriteSingleRegister(1, 3, 17));
wire.OnWrite = _ => wire.Receive(Fresh);
Assert.Null(wire.Client.ReadHoldingRegisters(20, 2, 17));
Assert.Single(wire.Writes);
wire.Receive(wire.Writes[0]);
Assert.Equal(new ushort[] { 42, 259 }, wire.Client.ReadHoldingRegisters(20, 2, 17));
}
private sealed class ScriptedPort : Stream
{
private readonly Queue<byte> _input = new();
internal ModbusRtuClient Client { get; }
internal List<byte[]> Writes { get; } = [];
internal Action<int>? OnWrite;
internal ScriptedPort() =>
Client = new ModbusRtuClient(new RtuSession(this, () => _input.Count, _input.Clear, 0));
internal void Receive(byte[] bytes)
{
foreach (byte value in bytes) _input.Enqueue(value);
}
public override int Read(byte[] buffer, int offset, int count)
{
if (_input.Count == 0) throw new TimeoutException();
int n = Math.Min(count, _input.Count);
for (int i = 0; i < n; i++) buffer[offset + i] = _input.Dequeue();
return n;
}
public override void Write(byte[] buffer, int offset, int count)
{
Writes.Add(buffer.AsSpan(offset, count).ToArray());
OnWrite?.Invoke(Writes.Count);
}
public override bool CanRead => true;
public override bool CanWrite => true;
public override bool CanSeek => false;
public override long Length => throw new NotSupportedException();
public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
public override void SetLength(long value) => throw new NotSupportedException();
public override void Flush() { }
}
}