Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 0 additions & 1 deletion ConfigFiles/MBE/connection/connection.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 0 additions & 1 deletion ConfigFiles/MOCVD/connection/connection.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
1 change: 0 additions & 1 deletion ConfigFiles/RIE/connection/connection.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 0 additions & 3 deletions SemiStep/SemiStep.Core/Configuration/Dto/ConnectionDto.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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; }

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
3 changes: 3 additions & 0 deletions SemiStep/SemiStep.Core/Plc/S7/IS7Driver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,9 @@ namespace SemiStep.Core.Plc.S7;

internal interface IS7Driver : IS7Transport, IAsyncDisposable
{
/// <summary>A read or write passed the transport deadline and the driver closed the client.</summary>
event Action? RequestDeadlinePassed;

Task ConnectAsync(PlcConnectionSettings settings);

Task DisconnectAsync();
Expand Down
2 changes: 1 addition & 1 deletion SemiStep/SemiStep.Core/Plc/S7/S7Di.cs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public static class S7Di
public static IServiceCollection AddS7(this IServiceCollection services)
{
services.AddSingleton<IPlcSyncOwnership, FileSyncOwnership>();
services.AddSingleton<S7Driver>();
services.AddSingleton(_ => new S7Driver(S7Driver.TransportDeadline));
services.AddSingleton<IS7Transport>(sp => sp.GetRequiredService<S7Driver>());
services.AddSingleton<RecipeConverter>();
services.AddSingleton(sp =>
Expand Down
107 changes: 100 additions & 7 deletions SemiStep/SemiStep.Core/Plc/S7/S7Driver.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,17 @@

namespace SemiStep.Core.Plc.S7;

internal sealed class S7Driver : IS7Driver
internal sealed class S7Driver(TimeSpan transportDeadline) : IS7Driver
{
/// <summary>The longest one PLC request may take: one connect attempt, or one PDU of a block read or write.</summary>
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;
Expand All @@ -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();
Expand All @@ -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,
Expand All @@ -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()
Expand All @@ -42,22 +63,94 @@ public Task DisconnectAsync()
return Task.CompletedTask;
}

public Task<byte[]> ReadBytesAsync(int dbNumber, int startByte, int count, CancellationToken ct = default)
public async Task<byte[]> 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<S7NetPlc, Task> transfer, CancellationToken ct)
{
try
{
await _serializer.RunAsync(() => transfer(RequirePlc()), ct);
}
catch (TimeoutException)
{
RequestDeadlinePassed?.Invoke();
throw;
}
}

private async Task RunWithDeadlineAsync(S7NetPlc plc, Func<CancellationToken, Task> 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);
}
}
70 changes: 47 additions & 23 deletions SemiStep/SemiStep.Core/Plc/S7/S7Service.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,18 +9,16 @@

namespace SemiStep.Core.Plc.S7;

internal sealed class S7Service(
IS7Driver transport,
PlcExecutionMonitor executionMonitor,
PlcTransactionExecutor transactionExecutor,
PlcConfiguration plcConfiguration,
ILogger<S7Service> 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<S7Service> _logger = logger;
private readonly IS7Driver _s7Driver;
private readonly PlcExecutionMonitor _plcExecutionMonitor;
private readonly PlcTransactionExecutor _plcTransactionExecutor;
private readonly PlcConfiguration _plcConfiguration;
private readonly ILogger<S7Service> _logger;
private readonly Lock _stateLock = new();

// The container calls DisposeAsync once per registration that resolved this instance.
Expand All @@ -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<S7Service> logger)
{
_s7Driver = s7Driver;
_plcExecutionMonitor = plcExecutionMonitor;
_plcTransactionExecutor = plcTransactionExecutor;
_plcConfiguration = plcConfiguration;
_logger = logger;
_s7Driver.RequestDeadlinePassed += OnRequestDeadlinePassed;
}

public PlcConnectionState State
{
get
Expand Down Expand Up @@ -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<PlcExecutionInfo> ExecutionState => executionMonitor.State;
public IObservable<PlcExecutionInfo> ExecutionState => _plcExecutionMonitor.State;

public DateTimeOffset? LastExchangeTime => transactionExecutor.LastExchangeTime;
public DateTimeOffset? LastExchangeTime => _plcTransactionExecutor.LastExchangeTime;

public event Action<PlcConnectionState>? StateChanged;

Expand Down Expand Up @@ -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;
Expand All @@ -136,7 +150,7 @@ public async Task DisconnectAsync()

public async Task<Result<PlcManagingAreaState>> 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)");
Expand All @@ -147,7 +161,7 @@ public async Task<Result<PlcManagingAreaState>> ReadManagingAreaAsync(Cancellati

public async Task<Result<Recipe>> 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)");
Expand All @@ -157,7 +171,7 @@ public async Task<Result<Recipe>> ReadRecipeFromPlcAsync(CancellationToken ct =

public async Task<Result<int>> 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)");
Expand All @@ -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;
Expand All @@ -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)
Expand Down Expand Up @@ -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)
{
Expand Down
Loading