按实际接收帧校验 Modbus RTU 写入和异常应答

This commit is contained in:
wanglei 2026-12-05 20:16:10 +08:00
parent e49e90329b
commit 3de85630c6
2 changed files with 51 additions and 84 deletions

View File

@ -95,20 +95,24 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
// ─── 读写串口 ───
private static bool ReadAll(System.IO.Ports.SerialPort port, byte[] buffer, int offset, int count)
// 保留响应的线上布局供 CRC 校验及 ReceiveData 使用。
internal static byte[] ReadResponse(Stream stream, byte functionCode)
{
int total = 0;
while (total < count)
{
try
{
int read = port.Read(buffer, offset + total, count - total);
if (read <= 0) return false;
total += read;
}
catch { return false; }
}
return true;
byte[] head = new byte[2];
stream.ReadExactly(head);
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 校验失败");
return response;
}
private byte[] Execute(byte unitId, byte functionCode, byte[] requestData)
@ -136,79 +140,11 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
if (waitMs < 20) waitMs = 20;
Thread.Sleep(waitMs);
// 读响应:先读头 2 字节(地址 + 功能码),再读后续
byte[] head = new byte[2];
if (!ReadAll(_port, head, 0, 2))
{
Log("ModbusRTU: 读响应头失败");
_port.DiscardInBuffer();
return null;
}
byte respFunc = head[1];
bool isError = (respFunc & 0x80) != 0;
// 确定 PDU 长度
int dataLen;
if (functionCode == FC_READ_HOLDING_REGISTERS && !isError)
{
// 读寄存器:功能码后跟字节数
byte[] bc = new byte[1];
if (!ReadAll(_port, bc, 0, 1))
{
_port.DiscardInBuffer();
return null;
}
dataLen = bc[0]; // 功能码 + 数据字节数
}
else if (!isError)
{
// 写操作:地址+功能码+数据固定 4 字节
dataLen = 4;
}
else
{
// 异常响应:地址+异常码共 1 字节数据
dataLen = 1;
}
// 读剩余 PDU 数据
byte[] pduExtra = new byte[dataLen];
if (!ReadAll(_port, pduExtra, 0, dataLen))
{
Log("ModbusRTU: 读 PDU 失败");
_port.DiscardInBuffer();
return null;
}
// 组合完整响应(不含 CRC)
byte[] response = [head[0], head[1], (byte)dataLen, .. pduExtra];
// 读 CRC(2 字节)
byte[] crcBytes = new byte[2];
if (!ReadAll(_port, crcBytes, 0, 2))
{
Log("ModbusRTU: 读 CRC 失败");
_port.DiscardInBuffer();
return null;
}
// 验证 CRC
ushort expectedCrc = CalcCrc(response, 0, response.Length);
ushort actualCrc = (ushort)(crcBytes[0] | (crcBytes[1] << 8));
if (expectedCrc != actualCrc)
{
Log($"ModbusRTU: CRC 校验失败 (期望={expectedCrc:X4}, 实际={actualCrc:X4})");
_port.DiscardInBuffer();
return null;
}
byte[] response = ReadResponse(_port.BaseStream, functionCode);
Log($"ModbusRx [{BitConverter.ToString(response).Replace("-", " ")}]");
if (isError)
if ((response[1] & 0x80) != 0)
{
byte code = pduExtra.Length > 0 ? pduExtra[0] : (byte)0;
Log($"ModbusRTU 异常: func=0x{respFunc & 0x7F:X2} code={code}");
Log($"ModbusRTU 异常: func=0x{response[1] & 0x7F:X2} code={response[2]}");
return null;
}
@ -216,6 +152,11 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
ReceiveData = response;
return response;
}
catch (InvalidDataException ex)
{
Log(ex.Message);
return null;
}
catch (TimeoutException)
{
Log("ModbusRTU: 读取超时");

View File

@ -0,0 +1,26 @@
using System.IO;
using PLCSharp.VVMs.Connects.ModbusRtu;
namespace PLCSharp.Tests;
public class ModbusRtuFramingTests
{
[Theory]
[InlineData(6, "1106000100039A9B", "110600010003")]
[InlineData(16, "1110000100021298", "111000010002")]
[InlineData(6, "118602C264", "118602")]
[InlineData(3, "110304000A01024BA1", "110304000A0102")]
public void ValidResponseKeepsWireLayout(byte function, string wire, string expected)
{
using var stream = new MemoryStream(Convert.FromHexString(wire));
Assert.Equal(Convert.FromHexString(expected), ModbusRtuClient.ReadResponse(stream, function));
Assert.Equal(stream.Length, stream.Position);
}
[Fact]
public void BadWriteResponseCrcIsRejected()
{
using var stream = new MemoryStream(Convert.FromHexString("1106000100030000"));
Assert.Throws<InvalidDataException>(() => ModbusRtuClient.ReadResponse(stream, 6));
}
}