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 应答功能码"); } } }