diff --git a/PLCSharpWpf/VVMs/Connects/ModbusResponse.cs b/PLCSharpWpf/VVMs/Connects/ModbusResponse.cs new file mode 100644 index 0000000..32255d5 --- /dev/null +++ b/PLCSharpWpf/VVMs/Connects/ModbusResponse.cs @@ -0,0 +1,31 @@ +using System.Buffers.Binary; +using System.IO; + +namespace PLCSharp.VVMs.Connects; + +internal static class ModbusResponse +{ + internal static void ValidatePdu(byte function, ReadOnlySpan requestData, ReadOnlySpan pdu) + { + if (pdu.Length == 2 && pdu[0] == (function | 0x80)) return; + if (pdu.IsEmpty || pdu[0] != function) + throw new InvalidDataException("Modbus 应答功能码或异常帧长度与请求不匹配"); + + switch (function) + { + case 0x03: + int count = BinaryPrimitives.ReadUInt16BigEndian(requestData[2..]); + if (count is >= 1 and <= 125 && pdu.Length == 2 + 2 * count && pdu[1] == 2 * count) + return; + throw new InvalidDataException("Modbus 应答寄存器数量与请求不匹配"); + case 0x05: + case 0x06: + case 0x10: + // 单写回显地址和值,多写回显起始地址和数量。 + if (pdu[1..].SequenceEqual(requestData[..4])) return; + throw new InvalidDataException("Modbus 写应答回显与请求不匹配"); + default: + throw new InvalidDataException("不支持的 Modbus 应答功能码"); + } + } +} diff --git a/PLCSharpWpf/VVMs/Connects/ModbusTcp/ModbusTcpClient.cs b/PLCSharpWpf/VVMs/Connects/ModbusTcp/ModbusTcpClient.cs index 8bf880f..fd03763 100644 --- a/PLCSharpWpf/VVMs/Connects/ModbusTcp/ModbusTcpClient.cs +++ b/PLCSharpWpf/VVMs/Connects/ModbusTcp/ModbusTcpClient.cs @@ -1,5 +1,6 @@ using PLCSharp.Core.Prism; using PLCSharp.Core.Tools; +using System.Buffers.Binary; using System.ComponentModel; using System.IO; using System.Net; @@ -152,53 +153,50 @@ namespace PLCSharp.VVMs.Connects.ModbusTcp return ms.ToArray(); } - private static bool ReadAll(NetworkStream stream, byte[] buffer, int offset, int count) + internal static byte[] ReadResponse(Stream stream, byte[] request) { - int total = 0; - while (total < count) - { - int read = stream.Read(buffer, offset + total, count - total); - if (read <= 0) return false; - total += read; - } - return true; + byte[] header = new byte[7]; + stream.ReadExactly(header); + if (!header.AsSpan(0, 4).SequenceEqual(request.AsSpan(0, 4)) || header[6] != request[6]) + throw new InvalidDataException("ModbusTCP 应答事务号、协议号或站号与请求不匹配"); + int length = BinaryPrimitives.ReadUInt16BigEndian(header.AsSpan(4)); + if (length is < 2 or > 254) + throw new InvalidDataException("ModbusTCP 应答长度无效"); + byte[] pdu = new byte[length - 1]; + stream.ReadExactly(pdu); + ModbusResponse.ValidatePdu(request[7], request.AsSpan(8), pdu); + return [.. header, .. pdu]; } private byte[] Execute(byte unitId, byte functionCode, byte[] requestData) { lock (_lock) { + Successful = false; + ReceiveData = null; if (!Connected) return null; - var stream = GetStream(); - if (stream == null) return null; try { + var stream = GetStream(); + if (stream == null) return null; byte[] request = BuildRequest(++_transactionId, unitId, functionCode, requestData); stream.Write(request, 0, request.Length); Log($"{DateTime.Now:HH:mm:ss:fff} ModbusTx [{BitConverter.ToString(request).Replace("-", " ")}]"); stream.ReadTimeout = 5000; - byte[] mbap = new byte[7]; - if (!ReadAll(stream, mbap, 0, 7)) { Log("ModbusTCP: 读MBAP失败"); return null; } - - ushort respLen = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(mbap, 4)); - byte[] pdu = new byte[respLen - 1]; - if (!ReadAll(stream, pdu, 0, pdu.Length)) { Log("ModbusTCP: 读PDU失败"); return null; } - - Log($"ModbusRx [{BitConverter.ToString(mbap).Replace("-", " ")} {BitConverter.ToString(pdu).Replace("-", " ")}]"); - - byte respFunc = pdu[0]; - if ((respFunc & 0x80) != 0) + var response = ReadResponse(stream, request); + Log($"ModbusRx [{BitConverter.ToString(response).Replace("-", " ")}]"); + if ((response[7] & 0x80) != 0) { - Log($"ModbusTCP 异常: func=0x{respFunc & 0x7F:X2} code={(pdu.Length > 1 ? pdu[1] : 0)}"); + Log($"ModbusTCP 异常: func=0x{functionCode:X2} code={response[8]}"); return null; } + ReceiveData = response; Successful = true; - ReceiveData = [.. mbap, .. pdu]; - return pdu.Length > 1 ? pdu[1..] : []; + return response[8..]; } catch (Exception ex) { @@ -232,8 +230,7 @@ namespace PLCSharp.VVMs.Connects.ModbusTcp for (int i = 0; i < count; i++) { int offset = 1 + i * 2; - if (offset + 1 < resp.Length) - registers[i] = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(resp, offset)); + registers[i] = (ushort)IPAddress.NetworkToHostOrder(BitConverter.ToInt16(resp, offset)); } return registers; } diff --git a/Tests/PLCSharp.Tests/ModbusTcpFramingTests.cs b/Tests/PLCSharp.Tests/ModbusTcpFramingTests.cs index abf8de1..6573069 100644 --- a/Tests/PLCSharp.Tests/ModbusTcpFramingTests.cs +++ b/Tests/PLCSharp.Tests/ModbusTcpFramingTests.cs @@ -1,5 +1,6 @@ using PLCSharp.VVMs.Connects.ModbusTcp; using System.Buffers.Binary; +using System.IO; namespace PLCSharp.Tests; @@ -20,4 +21,41 @@ public class ModbusTcpFramingTests Assert.Equal(function, frame[7]); Assert.Equal(data, frame[8..]); } + [Theory] + [InlineData("123500000006110600010003")] // 前一笔事务 + [InlineData("123400010006110600010003")] // 其他协议 + [InlineData("123400000006120600010003")] // 其他站号 + [InlineData("123400000006110500010003")] // 其他功能 + [InlineData("123400000006110600020003")] // 写入地址不一致 + [InlineData("123400000006110600010004")] // 写入值不一致 + [InlineData("123400000003118502")] // 其他功能的异常 + [InlineData("12340000000411860200")] // 异常帧多出数据 + [InlineData("12340000000111")] // 无功能码 + public void MismatchedWriteResponseIsRejected(string hex) + { + using var stream = new MemoryStream(Convert.FromHexString(hex)); + var request = ModbusTcpClient.BuildRequest(0x1234, 0x11, 6, [0, 1, 0, 3]); + Assert.Throws(() => ModbusTcpClient.ReadResponse(stream, request)); + } + + [Theory] + [InlineData(3, "00010002", "0302000A", false)] + [InlineData(3, "00010002", "0304000A", false)] + [InlineData(3, "00010002", "0304000A0102", true)] + [InlineData(5, "0001FF00", "0500010000", false)] + [InlineData(5, "0001FF00", "050001FF00", true)] + [InlineData(6, "00010003", "0600010003", true)] + [InlineData(16, "0001000204000A0102", "1000010001", false)] + [InlineData(16, "0001000204000A0102", "1000010002", true)] + [InlineData(6, "00010003", "8602", true)] // 合法设备异常,由调用方报告失败 + public void ResponseMustMatchRequestedOperation(byte function, string data, string responsePdu, bool valid) + { + var request = ModbusTcpClient.BuildRequest(1, 17, function, Convert.FromHexString(data)); + var pdu = Convert.FromHexString(responsePdu); + byte[] frame = [0, 1, 0, 0, 0, (byte)(pdu.Length + 1), 17, .. pdu]; + using var stream = new MemoryStream(frame); + if (valid) Assert.Equal(frame, ModbusTcpClient.ReadResponse(stream, request)); + else Assert.Throws(() => ModbusTcpClient.ReadResponse(stream, request)); + } + }