62 lines
2.8 KiB
C#
62 lines
2.8 KiB
C#
using PLCSharp.VVMs.Connects.ModbusTcp;
|
|
using System.Buffers.Binary;
|
|
using System.IO;
|
|
|
|
namespace PLCSharp.Tests;
|
|
|
|
public class ModbusTcpFramingTests
|
|
{
|
|
[Theory]
|
|
[InlineData(3, "006B0003")]
|
|
[InlineData(5, "0005FF00")]
|
|
[InlineData(6, "00010003")]
|
|
[InlineData(16, "0001000204000A0102")]
|
|
public void HeaderLengthMatchesEntireUnitAndPdu(byte function, string hexData)
|
|
{
|
|
var data = Convert.FromHexString(hexData);
|
|
var frame = ModbusTcpClient.BuildRequest(0x1234, 0x11, function, data);
|
|
Assert.Equal(frame.Length - 6, BinaryPrimitives.ReadUInt16BigEndian(frame.AsSpan(4)));
|
|
Assert.Equal(new byte[] { 0x12, 0x34, 0, 0 }, frame[..4]);
|
|
Assert.Equal((byte)0x11, frame[6]);
|
|
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<InvalidDataException>(() => 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<InvalidDataException>(() => ModbusTcpClient.ReadResponse(stream, request));
|
|
}
|
|
|
|
}
|