diff --git a/ConfigFiles/MBE/connection/connection.yaml b/ConfigFiles/MBE/connection/connection.yaml index f0b46bf5..cf9398a2 100644 --- a/ConfigFiles/MBE/connection/connection.yaml +++ b/ConfigFiles/MBE/connection/connection.yaml @@ -9,7 +9,6 @@ plc_slot: 1 # -- Protocol settings -- max_retries_attempts: 3 polling_interval_ms: 100 -writing_timeout_ms: 5000 commit_timeout_ms: 5000 keep_alive_interval_ms: 5000 diff --git a/ConfigFiles/MOCVD/connection/connection.yaml b/ConfigFiles/MOCVD/connection/connection.yaml index f0b46bf5..cf9398a2 100644 --- a/ConfigFiles/MOCVD/connection/connection.yaml +++ b/ConfigFiles/MOCVD/connection/connection.yaml @@ -9,7 +9,6 @@ plc_slot: 1 # -- Protocol settings -- max_retries_attempts: 3 polling_interval_ms: 100 -writing_timeout_ms: 5000 commit_timeout_ms: 5000 keep_alive_interval_ms: 5000 diff --git a/ConfigFiles/RIE/connection/connection.yaml b/ConfigFiles/RIE/connection/connection.yaml index f0b46bf5..cf9398a2 100644 --- a/ConfigFiles/RIE/connection/connection.yaml +++ b/ConfigFiles/RIE/connection/connection.yaml @@ -9,7 +9,6 @@ plc_slot: 1 # -- Protocol settings -- max_retries_attempts: 3 polling_interval_ms: 100 -writing_timeout_ms: 5000 commit_timeout_ms: 5000 keep_alive_interval_ms: 5000 diff --git a/SemiStep/SemiStep.Core/Configuration/Dto/ConnectionDto.cs b/SemiStep/SemiStep.Core/Configuration/Dto/ConnectionDto.cs index fad5e313..a7dd3606 100644 --- a/SemiStep/SemiStep.Core/Configuration/Dto/ConnectionDto.cs +++ b/SemiStep/SemiStep.Core/Configuration/Dto/ConnectionDto.cs @@ -25,9 +25,6 @@ internal sealed class ConnectionDto [YamlMember(Alias = "polling_interval_ms")] public int? PollingIntervalMs { get; set; } - [YamlMember(Alias = "writing_timeout_ms")] - public int? WritingTimeoutMs { get; set; } - [YamlMember(Alias = "commit_timeout_ms")] public int? CommitTimeoutMs { get; set; } diff --git a/SemiStep/SemiStep.Core/Configuration/Mapping/ConnectionMapper.cs b/SemiStep/SemiStep.Core/Configuration/Mapping/ConnectionMapper.cs index d97b1ccb..08480275 100644 --- a/SemiStep/SemiStep.Core/Configuration/Mapping/ConnectionMapper.cs +++ b/SemiStep/SemiStep.Core/Configuration/Mapping/ConnectionMapper.cs @@ -46,7 +46,6 @@ private static PlcProtocolSettings MapProtocolSettings(ConnectionDto dto) return new PlcProtocolSettings( MaxRetryAttempts: dto.MaxRetriesAttempts ?? defaults.MaxRetryAttempts, PollingIntervalMs: dto.PollingIntervalMs ?? defaults.PollingIntervalMs, - WritingTimeoutMs: dto.WritingTimeoutMs ?? defaults.WritingTimeoutMs, CommitTimeoutMs: dto.CommitTimeoutMs ?? defaults.CommitTimeoutMs, KeepAliveIntervalMs: dto.KeepAliveIntervalMs ?? defaults.KeepAliveIntervalMs); } diff --git a/SemiStep/SemiStep.Core/Plc/Configuration/PlcProtocolSettings.cs b/SemiStep/SemiStep.Core/Plc/Configuration/PlcProtocolSettings.cs index 9a6452ff..21e9f325 100644 --- a/SemiStep/SemiStep.Core/Plc/Configuration/PlcProtocolSettings.cs +++ b/SemiStep/SemiStep.Core/Plc/Configuration/PlcProtocolSettings.cs @@ -3,14 +3,12 @@ public sealed record PlcProtocolSettings( int MaxRetryAttempts, int PollingIntervalMs, - int WritingTimeoutMs, int CommitTimeoutMs, int KeepAliveIntervalMs) { public static PlcProtocolSettings Default => new( MaxRetryAttempts: 3, PollingIntervalMs: 100, - WritingTimeoutMs: 5000, CommitTimeoutMs: 5000, KeepAliveIntervalMs: 5000); } diff --git a/SemiStep/SemiStep.Core/Plc/S7/IS7Driver.cs b/SemiStep/SemiStep.Core/Plc/S7/IS7Driver.cs index 26313af6..b87a520c 100644 --- a/SemiStep/SemiStep.Core/Plc/S7/IS7Driver.cs +++ b/SemiStep/SemiStep.Core/Plc/S7/IS7Driver.cs @@ -4,6 +4,9 @@ namespace SemiStep.Core.Plc.S7; internal interface IS7Driver : IS7Transport, IAsyncDisposable { + /// A read or write passed the transport deadline and the driver closed the client. + event Action? RequestDeadlinePassed; + Task ConnectAsync(PlcConnectionSettings settings); Task DisconnectAsync(); diff --git a/SemiStep/SemiStep.Core/Plc/S7/S7Di.cs b/SemiStep/SemiStep.Core/Plc/S7/S7Di.cs index 33dcbf40..066903de 100644 --- a/SemiStep/SemiStep.Core/Plc/S7/S7Di.cs +++ b/SemiStep/SemiStep.Core/Plc/S7/S7Di.cs @@ -15,7 +15,7 @@ public static class S7Di public static IServiceCollection AddS7(this IServiceCollection services) { services.AddSingleton(); - services.AddSingleton(); + services.AddSingleton(_ => new S7Driver(S7Driver.TransportDeadline)); services.AddSingleton(sp => sp.GetRequiredService()); services.AddSingleton(); services.AddSingleton(sp => diff --git a/SemiStep/SemiStep.Core/Plc/S7/S7Driver.cs b/SemiStep/SemiStep.Core/Plc/S7/S7Driver.cs index 99dbf0c8..1e043ef9 100644 --- a/SemiStep/SemiStep.Core/Plc/S7/S7Driver.cs +++ b/SemiStep/SemiStep.Core/Plc/S7/S7Driver.cs @@ -6,8 +6,17 @@ namespace SemiStep.Core.Plc.S7; -internal sealed class S7Driver : IS7Driver +internal sealed class S7Driver(TimeSpan transportDeadline) : IS7Driver { + /// The longest one PLC request may take: one connect attempt, or one PDU of a block read or write. + public static readonly TimeSpan TransportDeadline = TimeSpan.FromSeconds(5); + + // S7netplus 0.20 splits an async read at MaxPDUSize - 18 bytes and an async write at MaxPDUSize - 35 bytes. + // A chunk of that size reaches the PLC as one request, so each request gets its own deadline. + private const int ReadRequestOverhead = 18; + private const int WriteRequestOverhead = 35; + + private readonly TimeSpan _transportDeadline = transportDeadline; private readonly TransportSerializer _serializer = new(); // Written by connect/disconnect (UI or reconnect thread), read by the poll, keep-alive and sync threads; @@ -16,6 +25,8 @@ internal sealed class S7Driver : IS7Driver public bool IsConnected => Volatile.Read(ref _plc)?.IsConnected ?? false; + public event Action? RequestDeadlinePassed; + public async ValueTask DisposeAsync() { await DisconnectAsync(); @@ -24,6 +35,8 @@ public async ValueTask DisposeAsync() public async Task ConnectAsync(PlcConnectionSettings settings) { + Interlocked.Exchange(ref _plc, null)?.Close(); + var plc = new S7NetPlc( S7NetCpuType.S71500, settings.IpAddress, @@ -32,7 +45,15 @@ public async Task ConnectAsync(PlcConnectionSettings settings) (short)settings.Slot); Volatile.Write(ref _plc, plc); - await plc.OpenAsync(); + using var deadline = new CancellationTokenSource(_transportDeadline); + try + { + await plc.OpenAsync(deadline.Token); + } + catch (Exception ex) when (deadline.IsCancellationRequested) + { + throw CloseOnDeadline(plc, ex); + } } public Task DisconnectAsync() @@ -42,22 +63,94 @@ public Task DisconnectAsync() return Task.CompletedTask; } - public Task ReadBytesAsync(int dbNumber, int startByte, int count, CancellationToken ct = default) + public async Task ReadBytesAsync(int dbNumber, int startByte, int count, CancellationToken ct = default) { - return _serializer.RunAsync( - () => RequirePlc().ReadBytesAsync(S7NetDataType.DataBlock, dbNumber, startByte, count, ct), + var bytes = new byte[count]; + await RunBlockTransferAsync( + async plc => + { + var chunkSize = ChunkSize(plc, ReadRequestOverhead); + for (var offset = 0; offset < count; offset += chunkSize) + { + var chunk = bytes.AsMemory(offset, Math.Min(chunkSize, count - offset)); + var chunkStart = startByte + offset; + await RunWithDeadlineAsync( + plc, + token => plc.ReadBytesAsync(chunk, S7NetDataType.DataBlock, dbNumber, chunkStart, token), + ct); + } + }, ct); + + return bytes; } public Task WriteBytesAsync(int dbNumber, int startByte, byte[] data, CancellationToken ct = default) { - return _serializer.RunAsync( - () => RequirePlc().WriteBytesAsync(S7NetDataType.DataBlock, dbNumber, startByte, data, ct), + return RunBlockTransferAsync( + async plc => + { + var chunkSize = ChunkSize(plc, WriteRequestOverhead); + for (var offset = 0; offset < data.Length; offset += chunkSize) + { + var chunk = data.AsMemory(offset, Math.Min(chunkSize, data.Length - offset)); + var chunkStart = startByte + offset; + await RunWithDeadlineAsync( + plc, + token => plc.WriteBytesAsync(S7NetDataType.DataBlock, dbNumber, chunkStart, chunk, token), + ct); + } + }, ct); } + private async Task RunBlockTransferAsync(Func transfer, CancellationToken ct) + { + try + { + await _serializer.RunAsync(() => transfer(RequirePlc()), ct); + } + catch (TimeoutException) + { + RequestDeadlinePassed?.Invoke(); + throw; + } + } + + private async Task RunWithDeadlineAsync(S7NetPlc plc, Func request, CancellationToken ct) + { + using var deadline = CancellationTokenSource.CreateLinkedTokenSource(ct); + deadline.CancelAfter(_transportDeadline); + try + { + await request(deadline.Token); + } + catch (Exception ex) when (deadline.IsCancellationRequested && !ct.IsCancellationRequested) + { + throw CloseOnDeadline(plc, ex); + } + } + + private static int ChunkSize(S7NetPlc plc, int requestOverhead) + { + var chunkSize = plc.MaxPDUSize - requestOverhead; + + return chunkSize > 0 + ? chunkSize + : throw new InvalidOperationException( + $"The negotiated PDU of {plc.MaxPDUSize} bytes has no room after a {requestOverhead}-byte request header"); + } + private S7NetPlc RequirePlc() { return Volatile.Read(ref _plc) ?? throw new DriverNotConnectedException(); } + + private TimeoutException CloseOnDeadline(S7NetPlc plc, Exception cause) + { + Interlocked.CompareExchange(ref _plc, null, plc); + plc.Close(); + + return new TimeoutException($"The PLC request passed the {_transportDeadline.TotalSeconds} s deadline", cause); + } } diff --git a/SemiStep/SemiStep.Core/Plc/S7/S7Service.cs b/SemiStep/SemiStep.Core/Plc/S7/S7Service.cs index 16796b15..d4282db9 100644 --- a/SemiStep/SemiStep.Core/Plc/S7/S7Service.cs +++ b/SemiStep/SemiStep.Core/Plc/S7/S7Service.cs @@ -9,18 +9,16 @@ namespace SemiStep.Core.Plc.S7; -internal sealed class S7Service( - IS7Driver transport, - PlcExecutionMonitor executionMonitor, - PlcTransactionExecutor transactionExecutor, - PlcConfiguration plcConfiguration, - ILogger logger) - : IS7Connection, IS7Reader, IS7ExecutionStream +internal sealed class S7Service : IS7Connection, IS7Reader, IS7ExecutionStream { private static readonly TimeSpan _reconnectInitialDelay = TimeSpan.FromSeconds(1); private static readonly TimeSpan _reconnectMaxDelay = TimeSpan.FromSeconds(30); - private readonly ILogger _logger = logger; + private readonly IS7Driver _s7Driver; + private readonly PlcExecutionMonitor _plcExecutionMonitor; + private readonly PlcTransactionExecutor _plcTransactionExecutor; + private readonly PlcConfiguration _plcConfiguration; + private readonly ILogger _logger; private readonly Lock _stateLock = new(); // The container calls DisposeAsync once per registration that resolved this instance. @@ -36,6 +34,21 @@ internal sealed class S7Service( private CancellationTokenSource? _keepAliveCts; private Task? _keepAliveTask; + public S7Service( + IS7Driver s7Driver, + PlcExecutionMonitor plcExecutionMonitor, + PlcTransactionExecutor plcTransactionExecutor, + PlcConfiguration plcConfiguration, + ILogger logger) + { + _s7Driver = s7Driver; + _plcExecutionMonitor = plcExecutionMonitor; + _plcTransactionExecutor = plcTransactionExecutor; + _plcConfiguration = plcConfiguration; + _logger = logger; + _s7Driver.RequestDeadlinePassed += OnRequestDeadlinePassed; + } + public PlcConnectionState State { get @@ -66,17 +79,18 @@ public async ValueTask DisposeAsync() return; } + _s7Driver.RequestDeadlinePassed -= OnRequestDeadlinePassed; await DisconnectAsync(); - executionMonitor.Dispose(); + _plcExecutionMonitor.Dispose(); } public bool IsConnected => State == PlcConnectionState.Connected; - public bool IsRecipeActive => executionMonitor.LastKnown.RecipeActive; + public bool IsRecipeActive => _plcExecutionMonitor.LastKnown.RecipeActive; - public IObservable ExecutionState => executionMonitor.State; + public IObservable ExecutionState => _plcExecutionMonitor.State; - public DateTimeOffset? LastExchangeTime => transactionExecutor.LastExchangeTime; + public DateTimeOffset? LastExchangeTime => _plcTransactionExecutor.LastExchangeTime; public event Action? StateChanged; @@ -123,11 +137,11 @@ public async Task DisconnectAsync() } } - await executionMonitor.StopAsync(); + await _plcExecutionMonitor.StopAsync(); - if (transport.IsConnected) + if (_s7Driver.IsConnected) { - await transport.DisconnectAsync(); + await _s7Driver.DisconnectAsync(); } State = PlcConnectionState.Disconnected; @@ -136,7 +150,7 @@ public async Task DisconnectAsync() public async Task> ReadManagingAreaAsync(CancellationToken ct = default) { - var result = await transactionExecutor.ReadManagingAreaAsync(ct); + var result = await _plcTransactionExecutor.ReadManagingAreaAsync(ct); if (result.IsFailed) { _logger.LogWarning("Failed to read managing area from PLC: {Reason}", result.Errors.Count > 0 ? result.Errors[0].Message : "(no message)"); @@ -147,7 +161,7 @@ public async Task> ReadManagingAreaAsync(Cancellati public async Task> ReadRecipeFromPlcAsync(CancellationToken ct = default) { - var result = await transactionExecutor.ReadRecipeFromPlcAsync(ct); + var result = await _plcTransactionExecutor.ReadRecipeFromPlcAsync(ct); if (result.IsFailed) { _logger.LogWarning("Failed to read recipe from PLC: {Reason}", result.Errors.Count > 0 ? result.Errors[0].Message : "(no message)"); @@ -157,7 +171,7 @@ public async Task> ReadRecipeFromPlcAsync(CancellationToken ct = public async Task> ReadProtocolVersionAsync(CancellationToken ct = default) { - var result = await transactionExecutor.ReadProtocolVersionAsync(ct); + var result = await _plcTransactionExecutor.ReadProtocolVersionAsync(ct); if (result.IsFailed) { _logger.LogWarning("Failed to read protocol version from PLC: {Reason}", result.Errors.Count > 0 ? result.Errors[0].Message : "(no message)"); @@ -180,12 +194,22 @@ internal void OnConnectionLost() StateChanged?.Invoke(PlcConnectionState.Disconnected); _ = StopKeepAlive(); - executionMonitor.Stop(); + _plcExecutionMonitor.Stop(); _logger.LogWarning("PLC connection lost"); StartReconnectLoop(); } + private void OnRequestDeadlinePassed() + { + // The timed-out request can be the execution poll, and OnConnectionLost waits for that poll to stop. + _ = Task.Run(OnConnectionLost).ContinueWith( + task => _logger.LogError(task.Exception, "Declaring PLC link loss after a passed transport deadline failed"), + CancellationToken.None, + TaskContinuationOptions.OnlyOnFaulted, + TaskScheduler.Default); + } + private async Task ConnectInternalAsync() { PlcConnectionSettings? settings; @@ -204,11 +228,11 @@ private async Task ConnectInternalAsync() try { - await transport.ConnectAsync(settings); + await _s7Driver.ConnectAsync(settings); State = PlcConnectionState.Connected; _logger.LogInformation("Connected to PLC at {IpAddress}", settings.IpAddress); - executionMonitor.Start(); + _plcExecutionMonitor.Start(); StartKeepAlive(); } catch (Exception ex) @@ -255,14 +279,14 @@ private void StartKeepAlive() private async Task KeepAliveLoopAsync(CancellationToken ct) { - var intervalMs = plcConfiguration.ProtocolSettings.KeepAliveIntervalMs; + var intervalMs = _plcConfiguration.ProtocolSettings.KeepAliveIntervalMs; while (!ct.IsCancellationRequested) { try { await Task.Delay(intervalMs, ct); - await transactionExecutor.KeepAliveReadAsync(ct); + await _plcTransactionExecutor.KeepAliveReadAsync(ct); } catch (OperationCanceledException) { diff --git a/SemiStep/SemiStep.Tests/S7/Helpers/FakeS7Driver.cs b/SemiStep/SemiStep.Tests/S7/Helpers/FakeS7Driver.cs index 882a8335..5624f4df 100644 --- a/SemiStep/SemiStep.Tests/S7/Helpers/FakeS7Driver.cs +++ b/SemiStep/SemiStep.Tests/S7/Helpers/FakeS7Driver.cs @@ -26,6 +26,13 @@ internal sealed class FakeS7Driver : IS7Driver public int DisposeCount { get; private set; } + /// The fake answers every request at once, so no request passes the transport deadline. + public event Action? RequestDeadlinePassed + { + add { } + remove { } + } + /// /// Directly sets the connected state, bypassing and /// . Useful for simulating mid-session connection drops. diff --git a/SemiStep/SemiStep.Tests/S7/Helpers/LoopbackS7Server.cs b/SemiStep/SemiStep.Tests/S7/Helpers/LoopbackS7Server.cs new file mode 100644 index 00000000..f4410415 --- /dev/null +++ b/SemiStep/SemiStep.Tests/S7/Helpers/LoopbackS7Server.cs @@ -0,0 +1,205 @@ +using System.Buffers.Binary; +using System.Collections.Concurrent; +using System.Net; +using System.Net.Sockets; + +using SemiStep.Core.Plc.Configuration; + +namespace SemiStep.Tests.S7.Helpers; + +internal enum LoopbackS7Behavior +{ + /// Accepts the TCP connection and never answers. + NeverAnswer, + + /// Confirms the ISO connection and the S7 setup, then never answers. + ConnectThenNeverAnswer, + + /// Answers block reads and writes from its own memory after a delay per request. + Answer, +} + +/// A loopback S7 server that speaks just enough of the protocol for S7netplus 0.20. +internal sealed class LoopbackS7Server : IAsyncDisposable +{ + private const int TpktHeaderLength = 4; + private const int FrameHeaderLength = 7; + private const byte ReadFunction = 0x04; + private const byte WriteFunction = 0x05; + private const int ItemLengthOffset = 23; + private const int ItemDbOffset = 25; + private const int ItemAddressOffset = 28; + private const int WriteDataOffset = 35; + private const int DbSize = 4096; + + private static readonly byte[] _connectionConfirm = + [ + 0x03, 0x00, 0x00, 0x16, + 0x11, 0xD0, 0x00, 0x01, 0x00, 0x01, 0x00, 0xC0, 0x01, 0x0A, 0xC1, 0x02, 0x01, 0x00, 0xC2, 0x02, 0x01, 0x02, + ]; + + private readonly LoopbackS7Behavior _behavior; + private readonly TimeSpan _responseDelay; + private readonly int _pduSize; + private readonly TcpListener _listener = new(IPAddress.Loopback, 0); + private readonly CancellationTokenSource _stop = new(); + private readonly ConcurrentDictionary _dataBlocks = new(); + private readonly Task _acceptLoop; + + // Changed by the accept loop and the per-connection tasks (thread pool), read by the test thread. + private int _acceptedCount; + private int _openCount; + private int _requestCount; + + public LoopbackS7Server(LoopbackS7Behavior behavior, TimeSpan responseDelay = default, int pduSize = 480) + { + _behavior = behavior; + _responseDelay = responseDelay; + _pduSize = pduSize; + _listener.Start(); + _acceptLoop = Task.Run(AcceptLoopAsync); + } + + public PlcConnectionSettings Settings => + new("127.0.0.1", ((IPEndPoint)_listener.LocalEndpoint).Port, Rack: 0, Slot: 1); + + public int AcceptedCount => Volatile.Read(ref _acceptedCount); + + /// Accepted connections the client has not closed yet. + public int OpenCount => Volatile.Read(ref _openCount); + + /// Block read and write requests answered. + public int RequestCount => Volatile.Read(ref _requestCount); + + public async ValueTask DisposeAsync() + { + await _stop.CancelAsync(); + _listener.Stop(); + try + { + await _acceptLoop; + } + catch (Exception ex) when (ex is OperationCanceledException or SocketException or ObjectDisposedException) + { + } + + _stop.Dispose(); + } + + private async Task AcceptLoopAsync() + { + while (!_stop.IsCancellationRequested) + { + var client = await _listener.AcceptTcpClientAsync(_stop.Token); + Interlocked.Increment(ref _acceptedCount); + Interlocked.Increment(ref _openCount); + _ = Task.Run(() => ServeAsync(client)); + } + } + + private async Task ServeAsync(TcpClient client) + { + using (client) + { + try + { + var stream = client.GetStream(); + if (_behavior != LoopbackS7Behavior.NeverAnswer) + { + await ReadFrameAsync(stream); + await stream.WriteAsync(_connectionConfirm, _stop.Token); + await ReadFrameAsync(stream); + await stream.WriteAsync(BuildSetupAck(), _stop.Token); + } + + if (_behavior == LoopbackS7Behavior.Answer) + { + await AnswerRequestsAsync(stream); + } + + var buffer = new byte[1024]; + while (await stream.ReadAsync(buffer, _stop.Token) > 0) + { + } + } + catch (Exception ex) when (ex is IOException or OperationCanceledException or EndOfStreamException) + { + } + finally + { + Interlocked.Decrement(ref _openCount); + } + } + } + + private async Task AnswerRequestsAsync(NetworkStream stream) + { + while (true) + { + var frame = await ReadFrameAsync(stream); + await Task.Delay(_responseDelay, _stop.Token); + var length = BinaryPrimitives.ReadUInt16BigEndian(frame.AsSpan(ItemLengthOffset)); + var dataBlock = _dataBlocks.GetOrAdd( + BinaryPrimitives.ReadUInt16BigEndian(frame.AsSpan(ItemDbOffset)), + _ => new byte[DbSize]); + var address = ((frame[ItemAddressOffset] << 16) | BinaryPrimitives.ReadUInt16BigEndian( + frame.AsSpan(ItemAddressOffset + 1))) >> 3; + + byte[] response; + if (frame[FrameHeaderLength + 10] == WriteFunction) + { + frame.AsSpan(WriteDataOffset, length).CopyTo(dataBlock.AsSpan(address)); + response = BuildFrame([.. AckHeader(parameterLength: 2, dataLength: 1), WriteFunction, 0x01, 0xFF]); + } + else + { + var payload = new byte[18 + length]; + byte[] header = [.. AckHeader(parameterLength: 2, dataLength: 0), ReadFunction, 0x01, 0xFF, 0x04]; + header.CopyTo(payload, 0); + BinaryPrimitives.WriteUInt16BigEndian(payload.AsSpan(16), (ushort)(length * 8)); + dataBlock.AsSpan(address, length).CopyTo(payload.AsSpan(18)); + response = BuildFrame(payload); + } + + Interlocked.Increment(ref _requestCount); + await stream.WriteAsync(response, _stop.Token); + } + } + + private byte[] BuildSetupAck() + { + byte[] payload = [.. AckHeader(parameterLength: 8, dataLength: 0), 0xF0, 0x00, 0x00, 0x01, 0x00, 0x01, 0x00, 0x00]; + BinaryPrimitives.WriteUInt16BigEndian(payload.AsSpan(18), (ushort)_pduSize); + + return BuildFrame(payload); + } + + private static byte[] AckHeader(byte parameterLength, byte dataLength) + { + return [0x32, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, parameterLength, 0x00, dataLength, 0x00, 0x00]; + } + + private static byte[] BuildFrame(byte[] s7Payload) + { + var frame = new byte[FrameHeaderLength + s7Payload.Length]; + frame[0] = 0x03; + BinaryPrimitives.WriteUInt16BigEndian(frame.AsSpan(2), (ushort)frame.Length); + frame[4] = 0x02; + frame[5] = 0xF0; + frame[6] = 0x80; + s7Payload.CopyTo(frame, FrameHeaderLength); + + return frame; + } + + private async Task ReadFrameAsync(NetworkStream stream) + { + var header = new byte[TpktHeaderLength]; + await stream.ReadExactlyAsync(header, _stop.Token); + var frame = new byte[BinaryPrimitives.ReadUInt16BigEndian(header.AsSpan(2))]; + header.CopyTo(frame, 0); + await stream.ReadExactlyAsync(frame.AsMemory(TpktHeaderLength), _stop.Token); + + return frame; + } +} diff --git a/SemiStep/SemiStep.Tests/S7/S7DriverDeadlineTests.cs b/SemiStep/SemiStep.Tests/S7/S7DriverDeadlineTests.cs new file mode 100644 index 00000000..42e65837 --- /dev/null +++ b/SemiStep/SemiStep.Tests/S7/S7DriverDeadlineTests.cs @@ -0,0 +1,206 @@ +using System.Diagnostics; + +using AwesomeAssertions; + +using SemiStep.Core.Plc.S7; +using SemiStep.Tests.Helpers; +using SemiStep.Tests.S7.Helpers; + +using Xunit; + +namespace SemiStep.Tests.S7; + +[Trait("Component", "S7")] +[Trait("Area", "TransportDeadline")] +[Trait("Category", "Integration")] +public sealed class S7DriverDeadlineTests +{ + internal static readonly TimeSpan Deadline = TimeSpan.FromMilliseconds(300); + internal static readonly TimeSpan DeadlineMargin = TimeSpan.FromSeconds(1.5); + + // Bounds every await, so a request without a deadline fails the test instead of hanging the run. + internal static readonly TimeSpan HangGuard = TimeSpan.FromSeconds(5); + + // At a PDU of 240 bytes S7netplus reads 222 and writes 205 bytes per request. + private const int SmallPduSize = 240; + private const int SmallPduReadChunk = 222; + private const int SmallPduWriteChunk = 205; + + // A write request header alone fills this PDU, so a write chunk would hold zero bytes. + private const int WriteHeaderOnlyPduSize = 35; + private const int BlockStart = 10; + private const int BlockLength = 600; + + [Fact] + public async Task ConnectAsync_PlcNeverAnswers_FailsWithinDeadlineAndClosesClient() + { + await using var server = new LoopbackS7Server(LoopbackS7Behavior.NeverAnswer); + await using var driver = new S7Driver(Deadline); + var stopwatch = Stopwatch.StartNew(); + + var connect = () => driver.ConnectAsync(server.Settings).WaitAsync(HangGuard, TestContext.Current.CancellationToken); + + await connect.Should().ThrowAsync().WithInnerException(); + stopwatch.Elapsed.Should().BeLessThan(Deadline + DeadlineMargin); + driver.IsConnected.Should().BeFalse(); + await WaitUntilAllClosedAsync(server); + } + + [Fact] + public async Task ReadBytesAsync_PlcNeverAnswers_FailsWithinDeadlineAndReleasesGate() + { + await using var server = new LoopbackS7Server(LoopbackS7Behavior.ConnectThenNeverAnswer); + await using var driver = new S7Driver(Deadline); + var deadlinePassedCount = 0; + driver.RequestDeadlinePassed += () => Interlocked.Increment(ref deadlinePassedCount); + await driver.ConnectAsync(server.Settings).WaitAsync(HangGuard, TestContext.Current.CancellationToken); + var stopwatch = Stopwatch.StartNew(); + + var read = () => driver.ReadBytesAsync(1, 0, 4).WaitAsync(HangGuard, TestContext.Current.CancellationToken); + + await read.Should().ThrowAsync().WithInnerException(); + stopwatch.Elapsed.Should().BeLessThan(Deadline + DeadlineMargin); + await AssertClientClosedAndGateFreeAsync(driver, server); + deadlinePassedCount.Should().Be(1); + } + + [Fact] + public async Task WriteBytesAsync_PlcNeverAnswers_FailsWithinDeadlineAndReleasesGate() + { + await using var server = new LoopbackS7Server(LoopbackS7Behavior.ConnectThenNeverAnswer); + await using var driver = new S7Driver(Deadline); + var deadlinePassedCount = 0; + driver.RequestDeadlinePassed += () => Interlocked.Increment(ref deadlinePassedCount); + await driver.ConnectAsync(server.Settings).WaitAsync(HangGuard, TestContext.Current.CancellationToken); + var stopwatch = Stopwatch.StartNew(); + + var write = () => driver.WriteBytesAsync(1, 0, [1, 2]).WaitAsync(HangGuard, TestContext.Current.CancellationToken); + + await write.Should().ThrowAsync().WithInnerException(); + stopwatch.Elapsed.Should().BeLessThan(Deadline + DeadlineMargin); + await AssertClientClosedAndGateFreeAsync(driver, server); + deadlinePassedCount.Should().Be(1); + } + + [Fact] + public async Task ConnectAsync_Repeated_ClosesEachPreviousClient() + { + await using var server = new LoopbackS7Server(LoopbackS7Behavior.ConnectThenNeverAnswer); + await using var driver = new S7Driver(Deadline); + + for (var attempt = 0; attempt < 3; attempt++) + { + await driver.ConnectAsync(server.Settings).WaitAsync(HangGuard, TestContext.Current.CancellationToken); + } + + await TestHelpers.WaitUntilAsync( + () => server.AcceptedCount == 3 && server.OpenCount == 1, + cancellationToken: TestContext.Current.CancellationToken); + driver.IsConnected.Should().BeTrue(); + } + + [Fact] + public async Task ConnectAsync_RepeatedPastDeadline_LeavesNoClientOpen() + { + await using var server = new LoopbackS7Server(LoopbackS7Behavior.NeverAnswer); + await using var driver = new S7Driver(Deadline); + + for (var attempt = 0; attempt < 3; attempt++) + { + var connect = () => driver.ConnectAsync(server.Settings).WaitAsync(HangGuard, TestContext.Current.CancellationToken); + await connect.Should().ThrowAsync().WithInnerException(); + } + + server.AcceptedCount.Should().Be(3); + await WaitUntilAllClosedAsync(server); + } + + [Fact] + public async Task ReadBytesAsync_CallerCancels_RaisesNoDeadlinePassed() + { + await using var server = new LoopbackS7Server(LoopbackS7Behavior.ConnectThenNeverAnswer); + await using var driver = new S7Driver(HangGuard); + var deadlinePassedCount = 0; + driver.RequestDeadlinePassed += () => Interlocked.Increment(ref deadlinePassedCount); + await driver.ConnectAsync(server.Settings).WaitAsync(HangGuard, TestContext.Current.CancellationToken); + using var callerCancel = new CancellationTokenSource(Deadline); + + var read = () => driver.ReadBytesAsync(1, 0, 4, callerCancel.Token) + .WaitAsync(HangGuard, TestContext.Current.CancellationToken); + + await read.Should().ThrowAsync(); + deadlinePassedCount.Should().Be(0); + } + + [Fact] + public async Task BlockTransfers_LongerThanDeadline_ArmAFreshDeadlinePerPdu() + { + var chunkDelay = TimeSpan.FromMilliseconds(500); + var deadline = TimeSpan.FromSeconds(1); + await using var server = new LoopbackS7Server(LoopbackS7Behavior.Answer, chunkDelay, pduSize: SmallPduSize); + await using var driver = new S7Driver(deadline); + await driver.ConnectAsync(server.Settings).WaitAsync(HangGuard, TestContext.Current.CancellationToken); + var written = Enumerable.Range(0, BlockLength).Select(index => (byte)(index % 251)).ToArray(); + var stopwatch = Stopwatch.StartNew(); + + await driver.WriteBytesAsync(1, BlockStart, written, TestContext.Current.CancellationToken).WaitAsync(HangGuard, TestContext.Current.CancellationToken); + var read = await driver.ReadBytesAsync(1, BlockStart, BlockLength, TestContext.Current.CancellationToken) + .WaitAsync(HangGuard, TestContext.Current.CancellationToken); + + read.Should().Equal(written); + server.RequestCount.Should().Be(6, "a 600-byte block is three write PDUs and three read PDUs at a PDU of 240"); + stopwatch.Elapsed.Should().BeGreaterThan(2 * deadline, "each block alone takes longer than one deadline"); + } + + [Fact] + public async Task BlockTransfers_ExactMultipleOfChunk_SendNoEmptyTrailingRequest() + { + await using var server = new LoopbackS7Server(LoopbackS7Behavior.Answer, pduSize: SmallPduSize); + await using var driver = new S7Driver(Deadline); + await driver.ConnectAsync(server.Settings).WaitAsync(HangGuard, TestContext.Current.CancellationToken); + var written = Enumerable.Range(0, 2 * SmallPduWriteChunk).Select(index => (byte)(index % 251)).ToArray(); + + await driver.WriteBytesAsync(1, BlockStart, written, TestContext.Current.CancellationToken) + .WaitAsync(HangGuard, TestContext.Current.CancellationToken); + var read = await driver.ReadBytesAsync(1, BlockStart, 2 * SmallPduReadChunk, TestContext.Current.CancellationToken) + .WaitAsync(HangGuard, TestContext.Current.CancellationToken); + + read.Take(written.Length).Should().Equal(written); + server.RequestCount.Should().Be(4, "two full write chunks and two full read chunks"); + } + + [Fact] + public async Task WriteBytesAsync_PduSmallerThanRequestHeader_ThrowsAndReleasesGate() + { + await using var server = new LoopbackS7Server(LoopbackS7Behavior.Answer, pduSize: WriteHeaderOnlyPduSize); + await using var driver = new S7Driver(Deadline); + await driver.ConnectAsync(server.Settings).WaitAsync(HangGuard, TestContext.Current.CancellationToken); + + // A zero-byte chunk would loop without yielding; Task.Run keeps that loop off the test thread for HangGuard. + var write = () => Task.Run(() => driver.WriteBytesAsync(1, 0, [1, 2]), TestContext.Current.CancellationToken) + .WaitAsync(HangGuard, TestContext.Current.CancellationToken); + + await write.Should().ThrowAsync(); + var read = await driver.ReadBytesAsync(1, 0, 4, TestContext.Current.CancellationToken) + .WaitAsync(HangGuard, TestContext.Current.CancellationToken); + read.Should().HaveCount(4, "a read header still fits, and the failed write left the transport gate free"); + } + + private static async Task AssertClientClosedAndGateFreeAsync(S7Driver driver, LoopbackS7Server server) + { + driver.IsConnected.Should().BeFalse(); + await WaitUntilAllClosedAsync(server); + + var nextRead = () => driver.ReadBytesAsync(1, 0, 4).WaitAsync(HangGuard, TestContext.Current.CancellationToken); + var stopwatch = Stopwatch.StartNew(); + await nextRead.Should().ThrowAsync(); + stopwatch.Elapsed.Should().BeLessThan(DeadlineMargin, "the next request enters the transport gate at once"); + } + + private static Task WaitUntilAllClosedAsync(LoopbackS7Server server) + { + return TestHelpers.WaitUntilAsync( + () => server.AcceptedCount > 0 && server.OpenCount == 0, + cancellationToken: TestContext.Current.CancellationToken); + } +} diff --git a/SemiStep/SemiStep.Tests/S7/S7DriverTests.cs b/SemiStep/SemiStep.Tests/S7/S7DriverTests.cs index f715312a..4fbd4fa2 100644 --- a/SemiStep/SemiStep.Tests/S7/S7DriverTests.cs +++ b/SemiStep/SemiStep.Tests/S7/S7DriverTests.cs @@ -14,7 +14,7 @@ public sealed class S7DriverTests [Fact] public async Task ReadBytesAsync_WithoutPlcInstance_ThrowsDriverNotConnected() { - await using var driver = new S7Driver(); + await using var driver = new S7Driver(S7DriverDeadlineTests.Deadline); var read = () => driver.ReadBytesAsync(1, 0, 1, TestContext.Current.CancellationToken); @@ -24,7 +24,7 @@ public async Task ReadBytesAsync_WithoutPlcInstance_ThrowsDriverNotConnected() [Fact] public async Task WriteBytesAsync_WithoutPlcInstance_ThrowsDriverNotConnected() { - await using var driver = new S7Driver(); + await using var driver = new S7Driver(S7DriverDeadlineTests.Deadline); await driver.DisconnectAsync(); var write = () => driver.WriteBytesAsync(1, 0, [0], TestContext.Current.CancellationToken); diff --git a/SemiStep/SemiStep.Tests/S7/S7ServiceDeadlineTests.cs b/SemiStep/SemiStep.Tests/S7/S7ServiceDeadlineTests.cs new file mode 100644 index 00000000..be21c122 --- /dev/null +++ b/SemiStep/SemiStep.Tests/S7/S7ServiceDeadlineTests.cs @@ -0,0 +1,87 @@ +using System.Diagnostics; + +using AwesomeAssertions; + +using SemiStep.Core.Plc.S7; +using SemiStep.Core.Plc.State; +using SemiStep.Core.Plc.Sync; +using SemiStep.Core.Recipes; +using SemiStep.Tests.Helpers; +using SemiStep.Tests.S7.Helpers; + +using Xunit; + +namespace SemiStep.Tests.S7; + +[Trait("Component", "S7")] +[Trait("Area", "TransportDeadline")] +[Trait("Category", "Integration")] +public sealed class S7ServiceDeadlineTests +{ + private const int NeverMs = 100000; + + private static readonly TimeSpan _deadline = S7DriverDeadlineTests.Deadline; + private static readonly TimeSpan _deadlineMargin = S7DriverDeadlineTests.DeadlineMargin; + private static readonly TimeSpan _hangGuard = S7DriverDeadlineTests.HangGuard; + + [Fact] + public async Task ReadPastDeadline_FailsAndDeclaresLinkLoss_ThenReconnects() + { + await using var server = new LoopbackS7Server(LoopbackS7Behavior.ConnectThenNeverAnswer); + await using var driver = new S7Driver(_deadline); + var configuration = S7ServiceTests.BuildConfiguration(keepAliveIntervalMs: NeverMs, pollingIntervalMs: NeverMs); + await using var service = S7ServiceTests.BuildService(configuration, driver).Service; + await service.ConnectAsync(server.Settings).WaitAsync(_hangGuard, TestContext.Current.CancellationToken); + var stopwatch = Stopwatch.StartNew(); + + var result = await service.ReadManagingAreaAsync(TestContext.Current.CancellationToken) + .WaitAsync(_hangGuard, TestContext.Current.CancellationToken); + + stopwatch.Elapsed.Should().BeLessThan(_deadline + _deadlineMargin); + result.HasError().Should().BeTrue(); + await TestHelpers.WaitUntilAsync( + () => service.State == PlcConnectionState.Disconnected, + cancellationToken: TestContext.Current.CancellationToken); + await TestHelpers.WaitUntilAsync( + () => server.AcceptedCount >= 2, + timeout: TimeSpan.FromSeconds(4), + pollInterval: TestHelpers.DefaultPollInterval, + cancellationToken: TestContext.Current.CancellationToken); + } + + [Fact] + public async Task PollPastDeadline_ReconnectsWithoutWaitingForThePollToStop() + { + await using var server = new LoopbackS7Server(LoopbackS7Behavior.ConnectThenNeverAnswer); + await using var driver = new S7Driver(_deadline); + var configuration = S7ServiceTests.BuildConfiguration(keepAliveIntervalMs: NeverMs, pollingIntervalMs: 50); + await using var service = S7ServiceTests.BuildService(configuration, driver).Service; + + await service.ConnectAsync(server.Settings).WaitAsync(_hangGuard, TestContext.Current.CancellationToken); + + // Deadline, the 1 s first reconnect delay and a margin; the 5 s poll stop timeout does not fit. + await TestHelpers.WaitUntilAsync( + () => server.AcceptedCount >= 2, + timeout: _deadline + TimeSpan.FromSeconds(1) + _deadlineMargin, + pollInterval: TestHelpers.DefaultPollInterval, + cancellationToken: TestContext.Current.CancellationToken); + } + + [Fact] + public async Task RecipeWritePastDeadline_IsAFailedWrite() + { + await using var server = new LoopbackS7Server(LoopbackS7Behavior.ConnectThenNeverAnswer); + await using var driver = new S7Driver(_deadline); + var configuration = S7ServiceTests.BuildConfiguration(keepAliveIntervalMs: NeverMs, pollingIntervalMs: NeverMs); + var (builtService, executor) = S7ServiceTests.BuildService(configuration, driver); + await using var service = builtService; + await service.ConnectAsync(server.Settings).WaitAsync(_hangGuard, TestContext.Current.CancellationToken); + var stopwatch = Stopwatch.StartNew(); + + var result = await executor.WriteRecipeWithRetryAsync(Recipe.Empty, TestContext.Current.CancellationToken) + .WaitAsync(_hangGuard, TestContext.Current.CancellationToken); + + stopwatch.Elapsed.Should().BeLessThan(_deadline + _deadlineMargin); + result.HasError().Should().BeTrue(); + } +} diff --git a/SemiStep/SemiStep.Tests/S7/S7ServiceTests.cs b/SemiStep/SemiStep.Tests/S7/S7ServiceTests.cs index 09927401..9dde90eb 100644 --- a/SemiStep/SemiStep.Tests/S7/S7ServiceTests.cs +++ b/SemiStep/SemiStep.Tests/S7/S7ServiceTests.cs @@ -61,6 +61,16 @@ internal static (S7Service Service, FakeS7Driver Driver) BuildService( ILogger? logger = null) { var driver = new FakeS7Driver(); + var (service, _) = BuildService(configuration, driver, logger); + + return (service, driver); + } + + internal static (S7Service Service, PlcTransactionExecutor Executor) BuildService( + PlcConfiguration configuration, + IS7Driver driver, + ILogger? logger = null) + { var converter = new RecipeConverter(BuildMinimalRecipeMetadataRegistry()); var arrayCodec = TestArrayCodecFactory.Create(configuration); var executor = new PlcTransactionExecutor( @@ -76,7 +86,7 @@ internal static (S7Service Service, FakeS7Driver Driver) BuildService( service = new S7Service( driver, monitor, executor, configuration, logger ?? NullLogger.Instance); - return (service, driver); + return (service, executor); } [Fact] diff --git a/SemiStep/SemiStep.Tests/YamlConfigs/Invalid/BrokenManagingDbLayout/connection/connection.yaml b/SemiStep/SemiStep.Tests/YamlConfigs/Invalid/BrokenManagingDbLayout/connection/connection.yaml index 5fb11a71..1b8cf599 100644 --- a/SemiStep/SemiStep.Tests/YamlConfigs/Invalid/BrokenManagingDbLayout/connection/connection.yaml +++ b/SemiStep/SemiStep.Tests/YamlConfigs/Invalid/BrokenManagingDbLayout/connection/connection.yaml @@ -9,7 +9,6 @@ plc_slot: 1 # -- Protocol settings -- max_retries_attempts: 3 polling_interval_ms: 100 -writing_timeout_ms: 5000 commit_timeout_ms: 5000 keep_alive_interval_ms: 5000 diff --git a/SemiStep/SemiStep.Tests/YamlConfigs/Standalone/FloatCultureInvariant/connection/connection.yaml b/SemiStep/SemiStep.Tests/YamlConfigs/Standalone/FloatCultureInvariant/connection/connection.yaml index 515c4a42..ef7817d1 100644 --- a/SemiStep/SemiStep.Tests/YamlConfigs/Standalone/FloatCultureInvariant/connection/connection.yaml +++ b/SemiStep/SemiStep.Tests/YamlConfigs/Standalone/FloatCultureInvariant/connection/connection.yaml @@ -9,7 +9,6 @@ plc_slot: 1 # -- Protocol settings -- max_retries_attempts: 3 polling_interval_ms: 100 -writing_timeout_ms: 5000 commit_timeout_ms: 5000 keep_alive_interval_ms: 5000 diff --git a/SemiStep/SemiStep.Tests/YamlConfigs/Standalone/NestedActionsValid/connection/connection.yaml b/SemiStep/SemiStep.Tests/YamlConfigs/Standalone/NestedActionsValid/connection/connection.yaml index 515c4a42..ef7817d1 100644 --- a/SemiStep/SemiStep.Tests/YamlConfigs/Standalone/NestedActionsValid/connection/connection.yaml +++ b/SemiStep/SemiStep.Tests/YamlConfigs/Standalone/NestedActionsValid/connection/connection.yaml @@ -9,7 +9,6 @@ plc_slot: 1 # -- Protocol settings -- max_retries_attempts: 3 polling_interval_ms: 100 -writing_timeout_ms: 5000 commit_timeout_ms: 5000 keep_alive_interval_ms: 5000 diff --git a/SemiStep/SemiStep.Tests/YamlConfigs/Standalone/UnknownYamlFields/connection/connection.yaml b/SemiStep/SemiStep.Tests/YamlConfigs/Standalone/UnknownYamlFields/connection/connection.yaml index 93834748..a8af7268 100644 --- a/SemiStep/SemiStep.Tests/YamlConfigs/Standalone/UnknownYamlFields/connection/connection.yaml +++ b/SemiStep/SemiStep.Tests/YamlConfigs/Standalone/UnknownYamlFields/connection/connection.yaml @@ -8,7 +8,6 @@ plc_slot: 1 max_retries_attempts: 3 polling_interval_ms: 100 -writing_timeout_ms: 5000 commit_timeout_ms: 5000 keep_alive_interval_ms: 5000 diff --git a/SemiStep/SemiStep.Tests/YamlConfigs/Standard/connection/connection.yaml b/SemiStep/SemiStep.Tests/YamlConfigs/Standard/connection/connection.yaml index 515c4a42..ef7817d1 100644 --- a/SemiStep/SemiStep.Tests/YamlConfigs/Standard/connection/connection.yaml +++ b/SemiStep/SemiStep.Tests/YamlConfigs/Standard/connection/connection.yaml @@ -9,7 +9,6 @@ plc_slot: 1 # -- Protocol settings -- max_retries_attempts: 3 polling_interval_ms: 100 -writing_timeout_ms: 5000 commit_timeout_ms: 5000 keep_alive_interval_ms: 5000 diff --git a/SemiStep/SemiStep.Tests/YamlConfigs/WideParams/connection/connection.yaml b/SemiStep/SemiStep.Tests/YamlConfigs/WideParams/connection/connection.yaml index 515c4a42..ef7817d1 100644 --- a/SemiStep/SemiStep.Tests/YamlConfigs/WideParams/connection/connection.yaml +++ b/SemiStep/SemiStep.Tests/YamlConfigs/WideParams/connection/connection.yaml @@ -9,7 +9,6 @@ plc_slot: 1 # -- Protocol settings -- max_retries_attempts: 3 polling_interval_ms: 100 -writing_timeout_ms: 5000 commit_timeout_ms: 5000 keep_alive_interval_ms: 5000 diff --git a/SemiStep/SemiStep.Tests/YamlConfigs/WithGroups/connection/connection.yaml b/SemiStep/SemiStep.Tests/YamlConfigs/WithGroups/connection/connection.yaml index 515c4a42..ef7817d1 100644 --- a/SemiStep/SemiStep.Tests/YamlConfigs/WithGroups/connection/connection.yaml +++ b/SemiStep/SemiStep.Tests/YamlConfigs/WithGroups/connection/connection.yaml @@ -9,7 +9,6 @@ plc_slot: 1 # -- Protocol settings -- max_retries_attempts: 3 polling_interval_ms: 100 -writing_timeout_ms: 5000 commit_timeout_ms: 5000 keep_alive_interval_ms: 5000 diff --git a/SemiStep/SemiStep.Tests/YamlConfigs/WithReadOnlyColumn/connection/connection.yaml b/SemiStep/SemiStep.Tests/YamlConfigs/WithReadOnlyColumn/connection/connection.yaml index 515c4a42..ef7817d1 100644 --- a/SemiStep/SemiStep.Tests/YamlConfigs/WithReadOnlyColumn/connection/connection.yaml +++ b/SemiStep/SemiStep.Tests/YamlConfigs/WithReadOnlyColumn/connection/connection.yaml @@ -9,7 +9,6 @@ plc_slot: 1 # -- Protocol settings -- max_retries_attempts: 3 polling_interval_ms: 100 -writing_timeout_ms: 5000 commit_timeout_ms: 5000 keep_alive_interval_ms: 5000 diff --git a/docs/architecture/error-reporting.md b/docs/architecture/error-reporting.md index dfeb73fa..d3826969 100644 --- a/docs/architecture/error-reporting.md +++ b/docs/architecture/error-reporting.md @@ -228,7 +228,12 @@ one `Debug` line without the stack. When a started recipe write ends without a l other source, `PlcSyncCoordinator` logs one Warning: the write was cancelled, it failed with `NotConnectedError`, or it failed after its outcome was dropped as stale. The `S7Service` keep-alive loop also calls the driver directly and treats any exception as a lost connection. Every other transport exception still becomes -`PlcCommandFailedError`. +`PlcCommandFailedError`. That includes the `TimeoutException` of a request that passes the transport deadline +(`S7Driver.TransportDeadline`, 5 s). `S7Driver` sends a block read or write as one call per PDU, at the PDU size +the PLC negotiated at connect, and each call has its own deadline. The driver then closes the client and raises +`RequestDeadlinePassed`, and `S7Service` declares link loss, so the reconnect loop runs. A connect attempt has the +same deadline, and its `TimeoutException` fails it like any other connect error: the first connect reports it to +its caller, and inside the reconnect loop the next attempt follows. **Un-laundering the fault seam.** The sync executor used to re-wrap a typed inner's `.Message` in a fresh `new Error(...)` before emitting the fault, discarding the type so `OnPlcFault`'s single-`IError` seam could diff --git a/docs/plans/20261130-recipe-replace-save-exit-safety.md b/docs/plans/20261130-recipe-replace-save-exit-safety.md index 8499e43a..dafd7e40 100644 --- a/docs/plans/20261130-recipe-replace-save-exit-safety.md +++ b/docs/plans/20261130-recipe-replace-save-exit-safety.md @@ -172,7 +172,7 @@ agent builds it as written: - A failed write is consumed and not re-queued (`PlcSyncCoordinator.cs:424-459`). Only a parked write retries (`:479-509`). - Teardown disposes `PlcSyncCoordinator`, which cancels the debounce (`PlcSyncCoordinator.cs:182`). The G4 send runs before teardown. Teardown runs after `App.Run` returns, bounded at 10 s (`SemiStep.UI/Program.cs:79-93`, `docs/architecture/exit-flow.md`), and stays there. - The reconnect loop's connect takes no token (`S7Driver.cs:35`), and `S7Service.DisconnectAsync` waits for that loop (`S7Service.cs:103-111`). The transport deadline on a connect attempt bounds both. -- ASSUMPTION: the S7 driver client returns from a hung connect, read or write when its token is cancelled, its own timeout passes, or the client is closed from another thread, and the transport gate is released afterwards; fallback: the deadline abandons the hung call, replaces the client, and releases the gate itself; checked by: the probe at the start of Task 3a, against a TCP listener that accepts and never answers. The result goes here as `probed:`. +- probed: S7netplus 0.20.0 against a loopback TCP listener that accepts and never answers, and against one that confirms the ISO connection and the S7 setup and then never answers (throwaway console, 2026-11-30). A cancelled token ends `OpenAsync`, `ReadBytesAsync` and `WriteBytesAsync` with `OperationCanceledException` about 20 ms after the cancel; `OpenAsync` to `192.0.2.1`, where no SYN is answered, also ends on the token. `Plc.Close()` from another thread ends all three with `IOException` or `PlcException`. `ReadTimeout` and `WriteTimeout` (default 10 000 ms) have no effect on the async calls: each call hung past 15 s, as it did with default settings. After a cancelled call the library has closed the client (`IsConnected` false, the next call throws `ObjectDisposedException`). A caller's cancel therefore also drops the connection. A `SemaphoreSlim` gate around a cancelled read was free afterwards; `S7DriverDeadlineTests` checks the same for `TransportSerializer`. Task 3a uses a per-request token: `S7Driver` cancels it at `S7Driver.TransportDeadline`, closes the client and throws `TimeoutException`. For a read or write it also raises `RequestDeadlinePassed` after the gate is released; a connect attempt only fails, as any connect error does. S7netplus splits a block into requests of `MaxPDUSize - 18` bytes for a read and `MaxPDUSize - 35` for an async write, all on one token, so `S7Driver` sends each block in chunks of that size, one call and one deadline per chunk. - The conflict signal fires without checking for other dialogs (`MainWindowViewModel.cs:113-117`), and the dialog shows step counts captured at detection (`:234-235`). - A null file path renders "Новый рецепт" (`MainWindowViewModel.cs:304-306`). `CurrentFilePath` has a private setter (`SemiStep.UI/RecipeFile/RecipeFileViewModel.cs:74-78`) that the reconnect take path (`SemiStep.UI/Coordinator/RecipeCoordinator.cs:400`) cannot reach. - Sync is never on at startup; the sync switch is its only trigger (`MainWindowViewModel.cs:213`). A fresh PLC emulator holds no recipe, shows the last write in a message line in its window, and loses its memory when it closes (`SemiStep.Tools.PlcEmulator/README.md`). diff --git a/docs/readme.md b/docs/readme.md index 0fe3fe3d..1115c32c 100644 --- a/docs/readme.md +++ b/docs/readme.md @@ -645,7 +645,6 @@ _Сообщение об ошибке соединения с ПЛК в пане | ------------------------ | ---------------------------------------------- | ------ | | `max_retries_attempts` | Число повторов записи при расхождении проверки | `3` | | `polling_interval_ms` | Период опроса области исполнения, мс | `100` | -| `writing_timeout_ms` | Таймаут записи, мс | `5000` | | `commit_timeout_ms` | Таймаут фиксации, мс | `5000` | | `keep_alive_interval_ms` | Период keep-alive, мс | `5000` | @@ -672,7 +671,6 @@ plc_slot: 1 # Настройки протокола max_retries_attempts: 3 polling_interval_ms: 100 -writing_timeout_ms: 5000 commit_timeout_ms: 5000 keep_alive_interval_ms: 5000