拒绝 CRC 正确但与请求不匹配的 Modbus RTU 应答
This commit is contained in:
parent
38401bb901
commit
4a96aa38e2
@ -96,10 +96,12 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
|
||||
// ─── 读写串口 ───
|
||||
|
||||
// 保留响应的线上布局供 CRC 校验及 ReceiveData 使用。
|
||||
internal static byte[] ReadResponse(Stream stream, byte functionCode)
|
||||
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;
|
||||
@ -112,6 +114,7 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
|
||||
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;
|
||||
}
|
||||
|
||||
@ -119,6 +122,8 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
|
||||
{
|
||||
lock (_lock)
|
||||
{
|
||||
Successful = false;
|
||||
ReceiveData = null;
|
||||
if (_port == null || !_port.IsOpen)
|
||||
{
|
||||
Log("ModbusRTU: 串口未打开");
|
||||
@ -140,7 +145,7 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
|
||||
if (waitMs < 20) waitMs = 20;
|
||||
Thread.Sleep(waitMs);
|
||||
|
||||
byte[] response = ReadResponse(_port.BaseStream, functionCode);
|
||||
byte[] response = ReadResponse(_port.BaseStream, unitId, functionCode, requestData);
|
||||
Log($"ModbusRx [{BitConverter.ToString(response).Replace("-", " ")}]");
|
||||
if ((response[1] & 0x80) != 0)
|
||||
{
|
||||
@ -148,8 +153,8 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
|
||||
return null;
|
||||
}
|
||||
|
||||
Successful = true;
|
||||
ReceiveData = response;
|
||||
Successful = true;
|
||||
return response;
|
||||
}
|
||||
catch (InvalidDataException ex)
|
||||
@ -199,13 +204,11 @@ namespace PLCSharp.VVMs.Connects.ModbusRtu
|
||||
if (response == null || response.Length < 3) return null;
|
||||
|
||||
// response = [addr, FC, byteCount, data...]
|
||||
byte byteCount = response[2];
|
||||
ushort[] registers = new ushort[count];
|
||||
for (int i = 0; i < count; i++)
|
||||
{
|
||||
int offset = 3 + i * 2;
|
||||
if (offset + 1 < response.Length)
|
||||
registers[i] = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(response, offset));
|
||||
registers[i] = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(response, offset));
|
||||
}
|
||||
return registers;
|
||||
}
|
||||
|
||||
@ -6,14 +6,14 @@ 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)
|
||||
[InlineData(6, "00010003", "1106000100039A9B", "110600010003")]
|
||||
[InlineData(16, "0001000204000A0102", "1110000100021298", "111000010002")]
|
||||
[InlineData(6, "00010003", "118602C264", "118602")]
|
||||
[InlineData(3, "00010002", "110304000A01024BA1", "110304000A0102")]
|
||||
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, function));
|
||||
Assert.Equal(Convert.FromHexString(expected), ModbusRtuClient.ReadResponse(stream, 17, function, Convert.FromHexString(request)));
|
||||
Assert.Equal(stream.Length, stream.Position);
|
||||
}
|
||||
|
||||
@ -21,6 +21,32 @@ public class ModbusRtuFramingTests
|
||||
public void BadWriteResponseCrcIsRejected()
|
||||
{
|
||||
using var stream = new MemoryStream(Convert.FromHexString("1106000100030000"));
|
||||
Assert.Throws<InvalidDataException>(() => ModbusRtuClient.ReadResponse(stream, 6));
|
||||
Assert.Throws<InvalidDataException>(() => ModbusRtuClient.ReadResponse(stream, 17, 6, [0, 1, 0, 3]));
|
||||
}
|
||||
[Theory]
|
||||
[InlineData(6, "00010003", "1206000100039AA8")]
|
||||
[InlineData(6, "00010003", "111000010003D358")]
|
||||
[InlineData(6, "00010003", "1106000200036A9B")]
|
||||
[InlineData(6, "00010003", "110600010004DB59")]
|
||||
[InlineData(16, "0001000204000A0102", "111000010003D358")]
|
||||
[InlineData(3, "00010002", "110302000AF980")]
|
||||
[InlineData(3, "00010001", "110304000A01024BA1")]
|
||||
[InlineData(6, "00010003", "118502C294")]
|
||||
[InlineData(6, "00010003", "1286023264")]
|
||||
public void ValidCrcDoesNotMakeAnUnrelatedReplySuccessful(byte function, string request, string wire)
|
||||
{
|
||||
using var stream = new MemoryStream(Convert.FromHexString(wire));
|
||||
Assert.Throws<InvalidDataException>(() =>
|
||||
ModbusRtuClient.ReadResponse(stream, 17, function, Convert.FromHexString(request)));
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void FailedRequestClearsPreviousSuccess()
|
||||
{
|
||||
var client = new ModbusRtuClient { Successful = true, ReceiveData = [1] };
|
||||
Assert.False(client.WriteSingleRegister(1, 3, 17));
|
||||
Assert.False(client.Successful);
|
||||
Assert.Null(client.ReceiveData);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Loading…
Reference in New Issue
Block a user