From 1ded47971b2a780e594205267bf61b618d3d0df8 Mon Sep 17 00:00:00 2001 From: Michael Croes Date: Mon, 31 May 2021 21:05:34 +0200 Subject: [PATCH 1/8] Consolidate async stream calls --- S7.Net/PlcAsynchronous.cs | 91 +++++++++++++++++++++------------------ 1 file changed, 48 insertions(+), 43 deletions(-) diff --git a/S7.Net/PlcAsynchronous.cs b/S7.Net/PlcAsynchronous.cs index de8f0c8..7730b3a 100644 --- a/S7.Net/PlcAsynchronous.cs +++ b/S7.Net/PlcAsynchronous.cs @@ -25,16 +25,15 @@ namespace S7.Net /// A task that represents the asynchronous open operation. public async Task OpenAsync(CancellationToken cancellationToken = default) { - var stream = await ConnectAsync().ConfigureAwait(false); + _stream = await ConnectAsync().ConfigureAwait(false); try { cancellationToken.ThrowIfCancellationRequested(); - await EstablishConnection(stream, cancellationToken).ConfigureAwait(false); - _stream = stream; + await EstablishConnection(cancellationToken).ConfigureAwait(false); } catch(Exception) { - stream.Dispose(); + _stream.Dispose(); throw; } } @@ -47,29 +46,28 @@ namespace S7.Net return tcpClient.GetStream(); } - private async Task EstablishConnection(NetworkStream stream, CancellationToken cancellationToken) + private async Task EstablishConnection(CancellationToken cancellationToken) { - await RequestConnection(stream, cancellationToken).ConfigureAwait(false); - await SetupConnection(stream, cancellationToken).ConfigureAwait(false); + await RequestConnection(cancellationToken).ConfigureAwait(false); + await SetupConnection(cancellationToken).ConfigureAwait(false); } - private async Task RequestConnection(NetworkStream stream, CancellationToken cancellationToken) + private async Task RequestConnection(CancellationToken cancellationToken) { var requestData = ConnectionRequest.GetCOTPConnectionRequest(CPU, Rack, Slot); - await stream.WriteAsync(requestData, 0, requestData.Length).ConfigureAwait(false); - var response = await COTP.TPDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false); + var response = await RequestTpduAsync(requestData, cancellationToken).ConfigureAwait(false); + if (response.PDUType != COTP.PduType.ConnectionConfirmed) { throw new InvalidDataException("Connection request was denied", response.TPkt.Data, 1, 0x0d); } } - private async Task SetupConnection(NetworkStream stream, CancellationToken cancellationToken) + private async Task SetupConnection(CancellationToken cancellationToken) { var setupData = GetS7ConnectionSetup(); - await stream.WriteAsync(setupData, 0, setupData.Length).ConfigureAwait(false); - var s7data = await COTP.TSDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false); + var s7data = await RequestTsduAsync(setupData, cancellationToken).ConfigureAwait(false); if (s7data.Length < 2) throw new WrongNumberOfBytesException("Not enough data received in response to Communication Setup"); @@ -112,7 +110,7 @@ namespace S7.Net } /// - /// Read and decode a certain number of bytes of the "VarType" provided. + /// Read and decode a certain number of bytes of the "VarType" provided. /// This can be used to read multiple consecutive variables of the same type (Word, DWord, Int, etc). /// If the read was not successful, check LastErrorCode or LastErrorString. /// @@ -179,10 +177,10 @@ namespace S7.Net } /// - /// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC. + /// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC. /// This reads only properties, it doesn't read private variable or public variable without {get;set;} specified. /// - /// Instance of the class that will store the values + /// Instance of the class that will store the values /// Index of the DB; es.: 1 is for DB1 /// Start byte address. If you want to read DB1.DBW200, this is 200. /// The token to monitor for cancellation requests. The default value is None. @@ -205,7 +203,7 @@ namespace S7.Net } /// - /// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC. + /// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC. /// This reads only properties, it doesn't read private variable or public variable without {get;set;} specified. To instantiate the class defined by the generic /// type, the class needs a default constructor. /// @@ -221,7 +219,7 @@ namespace S7.Net } /// - /// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC. + /// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC. /// This reads only properties, it doesn't read private variable or public variable without {get;set;} specified. /// /// The class that will be instantiated @@ -245,10 +243,10 @@ namespace S7.Net } /// - /// Reads multiple vars in a single request. + /// Reads multiple vars in a single request. /// You have to create and pass a list of DataItems and you obtain in response the same list with the values. /// Values are stored in the property "Value" of the dataItem and are already converted. - /// If you don't want the conversion, just create a dataItem of bytes. + /// If you don't want the conversion, just create a dataItem of bytes. /// The number of DataItems as well as the total size of the requested data can not exceed a certain limit (protocol restriction). /// /// List of dataitems that contains the list of variables that must be read. @@ -256,18 +254,15 @@ namespace S7.Net /// Please note that cancellation is advisory/cooperative and will not lead to immediate cancellation in all cases. public async Task> ReadMultipleVarsAsync(List dataItems, CancellationToken cancellationToken = default) { - //Snap7 seems to choke on PDU sizes above 256 even if snap7 + //Snap7 seems to choke on PDU sizes above 256 even if snap7 //replies with bigger PDU size in connection setup. AssertPduSizeForRead(dataItems); - var stream = GetStreamIfAvailable(); - try { var dataToSend = BuildReadRequestPackage(dataItems.Select(d => DataItem.GetDataItemAddress(d)).ToList()); - await stream.WriteAsync(dataToSend, 0, dataToSend.Length).ConfigureAwait(false); + var s7data = await RequestTsduAsync(dataToSend, cancellationToken); - var s7data = await COTP.TSDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false); ValidateResponseCode((ReadWriteErrorCode)s7data[14]); ParseDataIntoDataItems(s7data, dataItems); @@ -435,12 +430,9 @@ namespace S7.Net private async Task ReadBytesWithSingleRequestAsync(DataType dataType, int db, int startByteAdr, byte[] buffer, int offset, int count, CancellationToken cancellationToken) { - var stream = GetStreamIfAvailable(); - var dataToSend = BuildReadRequestPackage(new [] { new DataItemAddress(dataType, db, startByteAdr, count)}); - await stream.WriteAsync(dataToSend, 0, dataToSend.Length, cancellationToken); - var s7data = await COTP.TSDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false); + var s7data = await RequestTsduAsync(dataToSend, cancellationToken); AssertReadResponse(s7data, count); Array.Copy(s7data, 18, buffer, offset, count); @@ -456,13 +448,11 @@ namespace S7.Net { AssertPduSizeForWrite(dataItems); - var stream = GetStreamIfAvailable(); - var message = new ByteArray(); var length = S7WriteMultiple.CreateRequest(message, dataItems); - await stream.WriteAsync(message.Array, 0, length).ConfigureAwait(false); - var response = await COTP.TSDU.ReadAsync(stream, CancellationToken.None).ConfigureAwait(false); + var response = await RequestTsduAsync(message.Array, 0, length).ConfigureAwait(false); + S7WriteMultiple.ParseResponse(response, response.Length, dataItems); } @@ -476,15 +466,11 @@ namespace S7.Net /// A task that represents the asynchronous write operation. private async Task WriteBytesWithASingleRequestAsync(DataType dataType, int db, int startByteAdr, byte[] value, int dataOffset, int count, CancellationToken cancellationToken) { - try { - var stream = GetStreamIfAvailable(); var dataToSend = BuildWriteBytesPackage(dataType, db, startByteAdr, value, dataOffset, count); + var s7data = await RequestTsduAsync(dataToSend, cancellationToken).ConfigureAwait(false); - await stream.WriteAsync(dataToSend, 0, dataToSend.Length, cancellationToken).ConfigureAwait(false); - - var s7data = await COTP.TSDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false); ValidateResponseCode((ReadWriteErrorCode)s7data[14]); } catch (OperationCanceledException) @@ -499,15 +485,11 @@ namespace S7.Net private async Task WriteBitWithASingleRequestAsync(DataType dataType, int db, int startByteAdr, int bitAdr, bool bitValue, CancellationToken cancellationToken) { - var stream = GetStreamIfAvailable(); - try { var dataToSend = BuildWriteBitPackage(dataType, db, startByteAdr, bitValue, bitAdr); + var s7data = await RequestTsduAsync(dataToSend, cancellationToken).ConfigureAwait(false); - await stream.WriteAsync(dataToSend, 0, dataToSend.Length).ConfigureAwait(false); - - var s7data = await COTP.TSDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false); ValidateResponseCode((ReadWriteErrorCode)s7data[14]); } catch (OperationCanceledException) @@ -528,5 +510,28 @@ namespace S7.Net } return _stream; } + + private async Task RequestTpduAsync(byte[] requestData, CancellationToken cancellationToken = default) + { + var stream = GetStreamIfAvailable(); + + await stream.WriteAsync(requestData, 0, requestData.Length, cancellationToken).ConfigureAwait(false); + var response = await COTP.TPDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false); + + return response; + } + + private Task RequestTsduAsync(byte[] requestData, CancellationToken cancellationToken = default) => + RequestTsduAsync(requestData, 0, requestData.Length, cancellationToken); + + private async Task RequestTsduAsync(byte[] requestData, int offset, int length, CancellationToken cancellationToken = default) + { + var stream = GetStreamIfAvailable(); + + await stream.WriteAsync(requestData, offset, length, cancellationToken).ConfigureAwait(false); + var response = await COTP.TSDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false); + + return response; + } } } From 2afed882316f3d81c085dae9f7881cfd6f57f858 Mon Sep 17 00:00:00 2001 From: Michael Croes Date: Mon, 31 May 2021 21:17:03 +0200 Subject: [PATCH 2/8] Consolidate sync stream calls --- S7.Net/PlcSynchronous.cs | 37 +++++++++++++++++-------------------- 1 file changed, 17 insertions(+), 20 deletions(-) diff --git a/S7.Net/PlcSynchronous.cs b/S7.Net/PlcSynchronous.cs index fb6c825..9f90f7a 100644 --- a/S7.Net/PlcSynchronous.cs +++ b/S7.Net/PlcSynchronous.cs @@ -298,7 +298,6 @@ namespace S7.Net private void ReadBytesWithSingleRequest(DataType dataType, int db, int startByteAdr, byte[] buffer, int offset, int count) { - var stream = GetStreamIfAvailable(); try { // first create the header @@ -309,9 +308,7 @@ namespace S7.Net BuildReadDataRequestPackage(package, dataType, db, startByteAdr, count); var dataToSend = package.ToArray(); - stream.Write(dataToSend, 0, dataToSend.Length); - - var s7data = COTP.TSDU.Read(stream); + var s7data = RequestTsdu(dataToSend); AssertReadResponse(s7data, count); Array.Copy(s7data, 18, buffer, offset, count); @@ -331,13 +328,11 @@ namespace S7.Net { AssertPduSizeForWrite(dataItems); - var stream = GetStreamIfAvailable(); var message = new ByteArray(); var length = S7WriteMultiple.CreateRequest(message, dataItems); - stream.Write(message.Array, 0, length); + var response = RequestTsdu(message.Array, 0, length); - var response = COTP.TSDU.Read(stream); S7WriteMultiple.ParseResponse(response, response.Length, dataItems); } @@ -345,12 +340,9 @@ namespace S7.Net { try { - var stream = GetStreamIfAvailable(); var dataToSend = BuildWriteBytesPackage(dataType, db, startByteAdr, value, dataOffset, count); + var s7data = RequestTsdu(dataToSend); - stream.Write(dataToSend, 0, dataToSend.Length); - - var s7data = COTP.TSDU.Read(stream); ValidateResponseCode((ReadWriteErrorCode)s7data[14]); } catch (Exception exc) @@ -425,14 +417,11 @@ namespace S7.Net private void WriteBitWithASingleRequest(DataType dataType, int db, int startByteAdr, int bitAdr, bool bitValue) { - var stream = GetStreamIfAvailable(); try { var dataToSend = BuildWriteBitPackage(dataType, db, startByteAdr, bitValue, bitAdr); + var s7data = RequestTsdu(dataToSend); - stream.Write(dataToSend, 0, dataToSend.Length); - - var s7data = COTP.TSDU.Read(stream); ValidateResponseCode((ReadWriteErrorCode)s7data[14]); } catch (Exception exc) @@ -453,8 +442,6 @@ namespace S7.Net { AssertPduSizeForRead(dataItems); - var stream = GetStreamIfAvailable(); - try { // first create the header @@ -468,9 +455,7 @@ namespace S7.Net } var dataToSend = package.ToArray(); - stream.Write(dataToSend, 0, dataToSend.Length); - - var s7data = COTP.TSDU.Read(stream); //TODO use Async + var s7data = RequestTsdu(dataToSend); ValidateResponseCode((ReadWriteErrorCode)s7data[14]); @@ -481,5 +466,17 @@ namespace S7.Net throw new PlcException(ErrorCode.ReadData, exc); } } + + private byte[] RequestTsdu(byte[] requestData) => RequestTsdu(requestData, 0, requestData.Length); + + private byte[] RequestTsdu(byte[] requestData, int offset, int length) + { + var stream = GetStreamIfAvailable(); + + stream.Write(requestData, offset, length); + var response = COTP.TSDU.Read(stream); + + return response; + } } } From 8ed1b840bcaaca35a80b7b608b9d70470339dbd4 Mon Sep 17 00:00:00 2001 From: Michael Croes Date: Mon, 31 May 2021 21:17:23 +0200 Subject: [PATCH 3/8] PlcSynchronous: Clenaup trailing whitespace --- S7.Net/PlcSynchronous.cs | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/S7.Net/PlcSynchronous.cs b/S7.Net/PlcSynchronous.cs index 9f90f7a..61b99af 100644 --- a/S7.Net/PlcSynchronous.cs +++ b/S7.Net/PlcSynchronous.cs @@ -54,7 +54,7 @@ namespace S7.Net } /// - /// Read and decode a certain number of bytes of the "VarType" provided. + /// Read and decode a certain number of bytes of the "VarType" provided. /// This can be used to read multiple consecutive variables of the same type (Word, DWord, Int, etc). /// If the read was not successful, check LastErrorCode or LastErrorString. /// @@ -115,10 +115,10 @@ namespace S7.Net /// - /// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC. + /// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC. /// This reads only properties, it doesn't read private variable or public variable without {get;set;} specified. /// - /// Instance of the class that will store the values + /// Instance of the class that will store the values /// Index of the DB; es.: 1 is for DB1 /// Start byte address. If you want to read DB1.DBW200, this is 200. /// The number of read bytes @@ -138,7 +138,7 @@ namespace S7.Net } /// - /// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC. + /// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC. /// This reads only properties, it doesn't read private variable or public variable without {get;set;} specified. To instantiate the class defined by the generic /// type, the class needs a default constructor. /// @@ -152,7 +152,7 @@ namespace S7.Net } /// - /// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC. + /// Reads all the bytes needed to fill a class in C#, starting from a certain address, and set all the properties values to the value that are read from the PLC. /// This reads only properties, it doesn't read private variable or public variable without {get;set;} specified. /// /// The class that will be instantiated @@ -186,7 +186,7 @@ namespace S7.Net while (count > 0) { //TODO: Figure out how to use MaxPDUSize here - //Snap7 seems to choke on PDU sizes above 256 even if snap7 + //Snap7 seems to choke on PDU sizes above 256 even if snap7 //replies with bigger PDU size in connection setup. var maxToWrite = Math.Min(count, MaxPDUSize - 28);//TODO tested only when the MaxPDUSize is 480 WriteBytesWithASingleRequest(dataType, db, startByteAdr + localIndex, value, localIndex, maxToWrite); @@ -431,10 +431,10 @@ namespace S7.Net } /// - /// Reads multiple vars in a single request. + /// Reads multiple vars in a single request. /// You have to create and pass a list of DataItems and you obtain in response the same list with the values. /// Values are stored in the property "Value" of the dataItem and are already converted. - /// If you don't want the conversion, just create a dataItem of bytes. + /// If you don't want the conversion, just create a dataItem of bytes. /// The number of DataItems as well as the total size of the requested data can not exceed a certain limit (protocol restriction). /// /// List of dataitems that contains the list of variables that must be read. From 5636b93a53cef44590727d752267186cce1c5740 Mon Sep 17 00:00:00 2001 From: Michael Croes Date: Mon, 31 May 2021 21:17:42 +0200 Subject: [PATCH 4/8] PlcSynchronous: Remove unused usings --- S7.Net/PlcSynchronous.cs | 2 -- 1 file changed, 2 deletions(-) diff --git a/S7.Net/PlcSynchronous.cs b/S7.Net/PlcSynchronous.cs index 61b99af..881b7bf 100644 --- a/S7.Net/PlcSynchronous.cs +++ b/S7.Net/PlcSynchronous.cs @@ -2,8 +2,6 @@ using System; using System.IO; using System.Collections.Generic; -using System.Linq; -using System.Net.Sockets; using S7.Net.Protocol; using S7.Net.Helper; From df4f258290e7f667b9828441454c5f11bac790f5 Mon Sep 17 00:00:00 2001 From: Michael Croes Date: Mon, 31 May 2021 21:23:32 +0200 Subject: [PATCH 5/8] Move GetStreamIfAvailable to PLC.cs --- S7.Net/PLC.cs | 11 +++++++++++ S7.Net/PlcAsynchronous.cs | 10 ---------- 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/S7.Net/PLC.cs b/S7.Net/PLC.cs index 3a73b4c..b7ede94 100644 --- a/S7.Net/PLC.cs +++ b/S7.Net/PLC.cs @@ -1,5 +1,6 @@ using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Net.Sockets; using S7.Net.Protocol; @@ -242,6 +243,16 @@ namespace S7.Net } } + private Stream GetStreamIfAvailable() + { + if (_stream == null) + { + throw new PlcException(ErrorCode.ConnectionError, "Plc is not connected"); + } + + return _stream; + } + #region IDisposable Support private bool disposedValue = false; // To detect redundant calls diff --git a/S7.Net/PlcAsynchronous.cs b/S7.Net/PlcAsynchronous.cs index 7730b3a..3e523d8 100644 --- a/S7.Net/PlcAsynchronous.cs +++ b/S7.Net/PlcAsynchronous.cs @@ -5,7 +5,6 @@ using System.Linq; using System.Net.Sockets; using System.Threading.Tasks; using S7.Net.Protocol; -using System.IO; using System.Threading; using S7.Net.Protocol.S7; @@ -502,15 +501,6 @@ namespace S7.Net } } - private Stream GetStreamIfAvailable() - { - if (_stream == null) - { - throw new PlcException(ErrorCode.ConnectionError, "Plc is not connected"); - } - return _stream; - } - private async Task RequestTpduAsync(byte[] requestData, CancellationToken cancellationToken = default) { var stream = GetStreamIfAvailable(); From 8035f71a1659b0129c80d1eff7e6a3d709b9225e Mon Sep 17 00:00:00 2001 From: Michael Croes Date: Mon, 31 May 2021 22:57:13 +0200 Subject: [PATCH 6/8] Apply synchronization to stream actions --- S7.Net/Internal/TaskQueue.cs | 28 ++++++++++++++++++++++++++++ S7.Net/PLC.cs | 3 +++ S7.Net/PlcAsynchronous.cs | 22 ++++++++++++++-------- S7.Net/PlcSynchronous.cs | 7 +------ 4 files changed, 46 insertions(+), 14 deletions(-) create mode 100644 S7.Net/Internal/TaskQueue.cs diff --git a/S7.Net/Internal/TaskQueue.cs b/S7.Net/Internal/TaskQueue.cs new file mode 100644 index 0000000..bd0cd6b --- /dev/null +++ b/S7.Net/Internal/TaskQueue.cs @@ -0,0 +1,28 @@ +using System; +using System.Threading; +using System.Threading.Tasks; + +namespace S7.Net.Internal +{ + internal class TaskQueue + { + private static readonly object Sentinel = new object(); + + private Task prev = Task.FromResult(Sentinel); + + public async Task Enqueue(Func> action) + { + var tcs = new TaskCompletionSource(); + await Interlocked.Exchange(ref prev, tcs.Task).ConfigureAwait(false); + + try + { + return await action.Invoke().ConfigureAwait(false); + } + finally + { + tcs.SetResult(Sentinel); + } + } + } +} \ No newline at end of file diff --git a/S7.Net/PLC.cs b/S7.Net/PLC.cs index b7ede94..6180ad5 100644 --- a/S7.Net/PLC.cs +++ b/S7.Net/PLC.cs @@ -3,6 +3,7 @@ using System.Collections.Generic; using System.IO; using System.Linq; using System.Net.Sockets; +using S7.Net.Internal; using S7.Net.Protocol; using S7.Net.Types; @@ -14,6 +15,8 @@ namespace S7.Net /// public partial class Plc : IDisposable { + private readonly TaskQueue queue = new TaskQueue(); + private const int CONNECTION_TIMED_OUT_ERROR_CODE = 10060; //TCP connection to device diff --git a/S7.Net/PlcAsynchronous.cs b/S7.Net/PlcAsynchronous.cs index 3e523d8..91c2922 100644 --- a/S7.Net/PlcAsynchronous.cs +++ b/S7.Net/PlcAsynchronous.cs @@ -501,27 +501,33 @@ namespace S7.Net } } - private async Task RequestTpduAsync(byte[] requestData, CancellationToken cancellationToken = default) + private Task RequestTpduAsync(byte[] requestData, CancellationToken cancellationToken = default) { var stream = GetStreamIfAvailable(); - await stream.WriteAsync(requestData, 0, requestData.Length, cancellationToken).ConfigureAwait(false); - var response = await COTP.TPDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false); + return queue.Enqueue(async () => + { + await stream.WriteAsync(requestData, 0, requestData.Length, cancellationToken).ConfigureAwait(false); + var response = await COTP.TPDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false); - return response; + return response; + }); } private Task RequestTsduAsync(byte[] requestData, CancellationToken cancellationToken = default) => RequestTsduAsync(requestData, 0, requestData.Length, cancellationToken); - private async Task RequestTsduAsync(byte[] requestData, int offset, int length, CancellationToken cancellationToken = default) + private Task RequestTsduAsync(byte[] requestData, int offset, int length, CancellationToken cancellationToken = default) { var stream = GetStreamIfAvailable(); - await stream.WriteAsync(requestData, offset, length, cancellationToken).ConfigureAwait(false); - var response = await COTP.TSDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false); + return queue.Enqueue(async () => + { + await stream.WriteAsync(requestData, offset, length, cancellationToken).ConfigureAwait(false); + var response = await COTP.TSDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false); - return response; + return response; + }); } } } diff --git a/S7.Net/PlcSynchronous.cs b/S7.Net/PlcSynchronous.cs index 881b7bf..80e4738 100644 --- a/S7.Net/PlcSynchronous.cs +++ b/S7.Net/PlcSynchronous.cs @@ -469,12 +469,7 @@ namespace S7.Net private byte[] RequestTsdu(byte[] requestData, int offset, int length) { - var stream = GetStreamIfAvailable(); - - stream.Write(requestData, offset, length); - var response = COTP.TSDU.Read(stream); - - return response; + return RequestTsduAsync(requestData, offset, length).GetAwaiter().GetResult(); } } } From e93a6563128431c5d5a2d1c607f9a83e635beb65 Mon Sep 17 00:00:00 2001 From: Michael Croes Date: Tue, 1 Jun 2021 20:28:34 +0200 Subject: [PATCH 7/8] Fix locking for OpenAsync --- S7.Net/PlcAsynchronous.cs | 69 ++++++++++++++++++++++----------------- 1 file changed, 39 insertions(+), 30 deletions(-) diff --git a/S7.Net/PlcAsynchronous.cs b/S7.Net/PlcAsynchronous.cs index 91c2922..5482ec9 100644 --- a/S7.Net/PlcAsynchronous.cs +++ b/S7.Net/PlcAsynchronous.cs @@ -1,6 +1,7 @@ using S7.Net.Types; using System; using System.Collections.Generic; +using System.IO; using System.Linq; using System.Net.Sockets; using System.Threading.Tasks; @@ -24,15 +25,21 @@ namespace S7.Net /// A task that represents the asynchronous open operation. public async Task OpenAsync(CancellationToken cancellationToken = default) { - _stream = await ConnectAsync().ConfigureAwait(false); + var stream = await ConnectAsync().ConfigureAwait(false); try { - cancellationToken.ThrowIfCancellationRequested(); - await EstablishConnection(cancellationToken).ConfigureAwait(false); + await queue.Enqueue(async () => + { + cancellationToken.ThrowIfCancellationRequested(); + await EstablishConnection(stream, cancellationToken).ConfigureAwait(false); + _stream = stream; + + return default(object); + }); } catch(Exception) { - _stream.Dispose(); + stream.Dispose(); throw; } } @@ -45,16 +52,16 @@ namespace S7.Net return tcpClient.GetStream(); } - private async Task EstablishConnection(CancellationToken cancellationToken) + private async Task EstablishConnection(Stream stream, CancellationToken cancellationToken) { - await RequestConnection(cancellationToken).ConfigureAwait(false); - await SetupConnection(cancellationToken).ConfigureAwait(false); + await RequestConnection(stream, cancellationToken).ConfigureAwait(false); + await SetupConnection(stream, cancellationToken).ConfigureAwait(false); } - private async Task RequestConnection(CancellationToken cancellationToken) + private async Task RequestConnection(Stream stream, CancellationToken cancellationToken) { var requestData = ConnectionRequest.GetCOTPConnectionRequest(CPU, Rack, Slot); - var response = await RequestTpduAsync(requestData, cancellationToken).ConfigureAwait(false); + var response = await NoLockRequestTpduAsync(stream, requestData, cancellationToken).ConfigureAwait(false); if (response.PDUType != COTP.PduType.ConnectionConfirmed) { @@ -62,11 +69,13 @@ namespace S7.Net } } - private async Task SetupConnection(CancellationToken cancellationToken) + private async Task SetupConnection(Stream stream, CancellationToken cancellationToken) { var setupData = GetS7ConnectionSetup(); - var s7data = await RequestTsduAsync(setupData, cancellationToken).ConfigureAwait(false); + var s7data = await NoLockRequestTsduAsync(stream, setupData, 0, setupData.Length, cancellationToken) + .ConfigureAwait(false); + if (s7data.Length < 2) throw new WrongNumberOfBytesException("Not enough data received in response to Communication Setup"); @@ -501,19 +510,6 @@ namespace S7.Net } } - private Task RequestTpduAsync(byte[] requestData, CancellationToken cancellationToken = default) - { - var stream = GetStreamIfAvailable(); - - return queue.Enqueue(async () => - { - await stream.WriteAsync(requestData, 0, requestData.Length, cancellationToken).ConfigureAwait(false); - var response = await COTP.TPDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false); - - return response; - }); - } - private Task RequestTsduAsync(byte[] requestData, CancellationToken cancellationToken = default) => RequestTsduAsync(requestData, 0, requestData.Length, cancellationToken); @@ -521,13 +517,26 @@ namespace S7.Net { var stream = GetStreamIfAvailable(); - return queue.Enqueue(async () => - { - await stream.WriteAsync(requestData, offset, length, cancellationToken).ConfigureAwait(false); - var response = await COTP.TSDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false); + return queue.Enqueue(() => + NoLockRequestTsduAsync(stream, requestData, offset, length, cancellationToken)); + } - return response; - }); + private static async Task NoLockRequestTpduAsync(Stream stream, byte[] requestData, + CancellationToken cancellationToken = default) + { + await stream.WriteAsync(requestData, 0, requestData.Length, cancellationToken).ConfigureAwait(false); + var response = await COTP.TPDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false); + + return response; + } + + private static async Task NoLockRequestTsduAsync(Stream stream, byte[] requestData, int offset, int length, + CancellationToken cancellationToken = default) + { + await stream.WriteAsync(requestData, offset, length, cancellationToken).ConfigureAwait(false); + var response = await COTP.TSDU.ReadAsync(stream, cancellationToken).ConfigureAwait(false); + + return response; } } } From f67b1e773f23262406c1e41cb9be1776a34e149e Mon Sep 17 00:00:00 2001 From: Michael Croes Date: Tue, 1 Jun 2021 20:59:20 +0200 Subject: [PATCH 8/8] Add missing ConfigureAwait in OpenAsync --- S7.Net/PlcAsynchronous.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/S7.Net/PlcAsynchronous.cs b/S7.Net/PlcAsynchronous.cs index 5482ec9..c7a5868 100644 --- a/S7.Net/PlcAsynchronous.cs +++ b/S7.Net/PlcAsynchronous.cs @@ -35,7 +35,7 @@ namespace S7.Net _stream = stream; return default(object); - }); + }).ConfigureAwait(false); } catch(Exception) {