diff --git a/S7.Net/PLC.cs b/S7.Net/PLC.cs index d997b7a..8d98d4f 100644 --- a/S7.Net/PLC.cs +++ b/S7.Net/PLC.cs @@ -218,6 +218,27 @@ namespace S7.Net .Sum(len => (len & 1) == 1 ? len + 1 : len); } + private static void AssertReadResponse(byte[] s7Data, int dataLength) + { + var expectedLength = dataLength + 18; + + PlcException NotEnoughBytes() => + new PlcException(ErrorCode.WrongNumberReceivedBytes, + $"Received {s7Data.Length} bytes: '{BitConverter.ToString(s7Data)}', expected {expectedLength} bytes.") + ; + + if (s7Data == null) + throw new PlcException(ErrorCode.WrongNumberReceivedBytes, "No s7Data received."); + + if (s7Data.Length < 15) throw NotEnoughBytes(); + + if (s7Data[14] != 0xff) + throw new PlcException(ErrorCode.ReadData, + $"Invalid response from PLC: '{BitConverter.ToString(s7Data)}'."); + + if (s7Data.Length < expectedLength) throw NotEnoughBytes(); + } + #region IDisposable Support private bool disposedValue = false; // To detect redundant calls diff --git a/S7.Net/PlcAsynchronous.cs b/S7.Net/PlcAsynchronous.cs index 2a2de3e..9e82c8d 100644 --- a/S7.Net/PlcAsynchronous.cs +++ b/S7.Net/PlcAsynchronous.cs @@ -388,8 +388,7 @@ namespace S7.Net await stream.WriteAsync(package.Array, 0, package.Array.Length); var s7data = await COTP.TSDU.ReadAsync(stream); - if (s7data == null || s7data[14] != 0xff) - throw new PlcException(ErrorCode.WrongNumberReceivedBytes); + AssertReadResponse(s7data, count); for (int cnt = 0; cnt < count; cnt++) bytes[cnt] = s7data[cnt + 18]; diff --git a/S7.Net/PlcSynchronous.cs b/S7.Net/PlcSynchronous.cs index 7d2ef01..c101b3e 100644 --- a/S7.Net/PlcSynchronous.cs +++ b/S7.Net/PlcSynchronous.cs @@ -353,8 +353,7 @@ namespace S7.Net stream.Write(package.Array, 0, package.Array.Length); var s7data = COTP.TSDU.Read(stream); - if (s7data == null || s7data[14] != 0xff) - throw new PlcException(ErrorCode.WrongNumberReceivedBytes); + AssertReadResponse(s7data, count); for (int cnt = 0; cnt < count; cnt++) bytes[cnt] = s7data[cnt + 18];