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
8 changes: 8 additions & 0 deletions SemiStep/SemiStep.Core/Plc/IPlcSyncService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ public interface IPlcSyncService

void HandleConnectionLost();

/// <summary>
/// Ends the write pause and writes the newest recipe notified during it, or <paramref name="screenRecipe"/> if none was.
/// </summary>
void EndWritePause(Recipe screenRecipe, bool isValid);

/// <summary>Ends the write pause and drops the recipe notified during it: the PLC already holds the screen recipe.</summary>
void EndWritePauseWithoutWrite();

/// <summary>
/// Completes when the attempt in flight at the call has ended; throws when <paramref name="ct"/> cancels first.
/// </summary>
Expand Down
3 changes: 3 additions & 0 deletions SemiStep/SemiStep.Core/Plc/IS7Connection.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,7 @@ public interface IS7Connection : IAsyncDisposable
event Action<PlcConnectionState>? StateChanged;
Task ConnectAsync(PlcConnectionSettings settings);
Task DisconnectAsync();

/// <summary>Closes the client and runs the link-loss path, as a failed keep-alive probe does.</summary>
void DeclareLinkLost();
}
123 changes: 123 additions & 0 deletions SemiStep/SemiStep.Core/Plc/PlcComparisonAnswers.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,123 @@
using FluentResults;

using Microsoft.Extensions.Logging;

using SemiStep.Core.Plc.Sync;
using SemiStep.Core.Recipes;

namespace SemiStep.Core.Plc;

/// <summary>
/// Answers to the offer a comparison made: the conflict answers and the reconnect take. Each runs on the UI thread
/// and counts only while its comparison is current.
/// </summary>
internal sealed class PlcComparisonAnswers(
RecipeSession session,
IPlcSyncService syncService,
PlcComparisonState state,
PlcSyncSwitch syncSwitch,
PlcConflictNotifier conflictNotifier,
ILogger logger)
{
private readonly RecipeSession _session = session;
private readonly IPlcSyncService _syncService = syncService;
private readonly PlcComparisonState _state = state;
private readonly PlcSyncSwitch _syncSwitch = syncSwitch;
private readonly PlcConflictNotifier _conflictNotifier = conflictNotifier;
private readonly ILogger _logger = logger;

/// <summary>
/// The comparison saw an empty screen recipe off the UI thread. A screen that has steps or unsaved changes by now
/// gets the conflict instead of the take.
/// </summary>
public Result<bool> ApplyRecipeFromPlc(Recipe recipe)
{
PlcRecipeConflict? conflict = null;
Result<bool> result;
lock (_state.Gate)
{
if (_state.TakeOfferLocked(offer => !offer.IsConflict && ReferenceEquals(offer.PlcRecipe, recipe)) is not
{ } offer)
{
_logger.LogInformation("PLC recipe take ignored: its comparison is stale");
return Result.Ok(false);
}

if (_session.Current.Steps.Count > 0 || _session.IsDirty)
{
_state.ConvertTakeToConflictLocked(offer);
conflict = new PlcRecipeConflict(offer.ComparisonId, _session.Current, recipe);
result = Result.Ok(false);
}
else
{
result = TakeLocked(recipe);
}
}

if (conflict is not null)
{
_conflictNotifier.Raise(conflict);
}

return result;
}

/// <summary>Returns whether the session recipe was replaced; an answer to a stale conflict changes nothing.</summary>
public Result<bool> ResolveConflict(long comparisonId, PlcConflictAnswer answer)
{
if (!Enum.IsDefined(answer))
{
throw new ArgumentOutOfRangeException(nameof(answer), answer, "Unnamed conflict answer");
}

lock (_state.Gate)
{
if (_state.TakeOfferLocked(offer => offer.IsConflict && offer.ComparisonId == comparisonId) is not { } offer)
{
_logger.LogInformation("PLC conflict answer {Answer} ignored: its comparison is stale", answer);
return Result.Ok(false);
}

switch (answer)
{
case PlcConflictAnswer.KeepLocal:
_syncService.EndWritePause(_session.Current, _session.IsValid);
return Result.Ok(false);
case PlcConflictAnswer.TakePlc:
return TakeLocked(offer.PlcRecipe);
case PlcConflictAnswer.Dismissed:
case PlcConflictAnswer.DialogShowFailed:
_syncSwitch.PostTurnOff(_state.TurnOffLocked(
new ConflictUnresolvedError(answer == PlcConflictAnswer.DialogShowFailed)));
return Result.Ok(false);
default:
throw new ArgumentOutOfRangeException(nameof(answer), answer, "Unnamed conflict answer");
}
}
}

/// <summary>The load notifies sync while the pause holds, so ending the pause next drops that recipe.</summary>
private Result<bool> TakeLocked(Recipe plcRecipe)
{
Result loadResult;
try
{
loadResult = _session.LoadAsCurrentValidated(plcRecipe);
}
catch (Exception ex)
{
_logger.LogError(ex, "Taking the PLC recipe threw");
loadResult = Result.Fail(new ExceptionalError(ex));
}

if (loadResult.IsFailed)
{
_syncSwitch.PostTurnOff(_state.TurnOffLocked(new PlcRecipeNotLoadedError(loadResult.Errors)));
return Result.Fail<bool>(loadResult.Errors);
}

_syncService.EndWritePauseWithoutWrite();
return Result.Ok(true).WithReasons(loadResult.Reasons);
}
}
218 changes: 218 additions & 0 deletions SemiStep/SemiStep.Core/Plc/PlcComparisonState.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,218 @@
using FluentResults;

using SemiStep.Core.Plc.Sync;

namespace SemiStep.Core.Plc;

/// <summary>
/// The comparison bookkeeping under one lock: the sync-on flag and period, the current comparison ID, its offer and
/// the failures in a row. A member named *Locked expects the caller to hold <see cref="Gate"/>.
/// </summary>
internal sealed class PlcComparisonState
{
internal const int FailedComparisonLimit = 3;

// Every field below is guarded by Gate. It is taken by the UI thread (sync switch, conflict answers, the
// reconnect take), the S7 connection callback, and the comparison task and posted turn-offs on the thread pool.
private bool _isSyncOn;
private long _syncPeriod;
private bool _isEnabling;
private bool _isConnectedDuringEnable;
private long _lastComparisonId;
private long _currentComparisonId;
private bool _isComparisonRunning;
private int _failedComparisonsInRow;
private PlcRecipeOffer? _offer;
private long _takeConvertedToConflictId;

public Lock Gate { get; } = new();

/// <summary>Starts a sync-on period; <paramref name="turnOnLocked"/> runs under the same lock.</summary>
public void TurnOn(Action turnOnLocked)
{
lock (Gate)
{
_syncPeriod++;
_failedComparisonsInRow = 0;
InvalidateLocked();
_isEnabling = true;
_isConnectedDuringEnable = false;
_isSyncOn = true;
turnOnLocked();
}
}

/// <summary>Ends the period and makes every comparison ID stale; <paramref name="turnOffLocked"/> runs under the same lock.</summary>
public void TurnOff(Action turnOffLocked)
{
lock (Gate)
{
InvalidateLocked();
_isSyncOn = false;
_isEnabling = false;
_isConnectedDuringEnable = false;
turnOffLocked();
}
}

/// <summary>Returns whether the connect raised Connected, so the first comparison is due.</summary>
public bool EndEnabling()
{
lock (Gate)
{
var isComparisonDue = _isEnabling && _isConnectedDuringEnable;
_isEnabling = false;
_isConnectedDuringEnable = false;

return isComparisonDue;
}
}

/// <summary>
/// Null while sync is off. A Connected raised during the enable only marks the first comparison as due: it starts
/// after the version read.
/// </summary>
public long? TryBeginComparison(bool isFromConnectedEvent)
{
lock (Gate)
{
if (!_isSyncOn)
{
return null;
}

if (isFromConnectedEvent && _isEnabling)
{
_isConnectedDuringEnable = true;
return null;
}

_currentComparisonId = ++_lastComparisonId;
_isComparisonRunning = true;
_offer = null;

return _currentComparisonId;
}
}

/// <summary>
/// A comparison the drop cuts counts as failed here, whichever of the drop and its failed read comes first: the
/// read that passed the transport deadline also raises the drop, on another thread.
/// </summary>
public SyncTurnOff? LoseLink(Action pauseLocked)
{
lock (Gate)
{
if (!_isSyncOn)
{
return null;
}

var isComparisonCut = _isComparisonRunning;
InvalidateLocked();
pauseLocked();

return isComparisonCut ? CountFailureLocked() : null;
}
}

/// <summary>Returns false for a stale failure, which neither closes the link nor counts.</summary>
public bool TryFail(long comparisonId, out SyncTurnOff? failureCapTurnOff)
{
lock (Gate)
{
failureCapTurnOff = null;
if (!IsCurrentLocked(comparisonId) || !_isComparisonRunning)
{
return false;
}

InvalidateLocked();
failureCapTurnOff = CountFailureLocked();
return true;
}
}

public bool TryDecideLocked(long comparisonId)
{
if (!IsCurrentLocked(comparisonId) || !_isComparisonRunning)
{
return false;
}

_isComparisonRunning = false;
_failedComparisonsInRow = 0;
return true;
}

public bool IsCurrentLocked(long comparisonId)
{
return comparisonId != 0 && comparisonId == _currentComparisonId;
}

public void OfferLocked(PlcRecipeOffer offer)
{
_offer = offer;
}

/// <summary>The screen changed before the reconnect take, so the same comparison offers a conflict instead.</summary>
public void ConvertTakeToConflictLocked(PlcRecipeOffer takeOffer)
{
_offer = takeOffer with { IsConflict = true };
_takeConvertedToConflictId = takeOffer.ComparisonId;
}

public bool WasTakeConvertedToConflict(long comparisonId)
{
lock (Gate)
{
return comparisonId != 0 && comparisonId == _takeConvertedToConflictId;
}
}

/// <summary>An offer is taken once; a stale or mismatched request leaves it in place.</summary>
public PlcRecipeOffer? TakeOfferLocked(Func<PlcRecipeOffer, bool> matches)
{
if (_offer is not { } offer || !IsCurrentLocked(offer.ComparisonId) || !matches(offer))
{
return null;
}

_offer = null;
return offer;
}

public SyncTurnOff TurnOffLocked(IError reason)
{
return new SyncTurnOff(_syncPeriod, reason, IsFailureCap: false);
}

/// <summary>
/// Checked when a posted turn-off runs: it is skipped when sync went off, a newer period started, or a later
/// comparison decided and reset the failures it counted.
/// </summary>
public bool IsDue(SyncTurnOff turnOff)
{
lock (Gate)
{
return _isSyncOn
&& turnOff.SyncPeriod == _syncPeriod
&& (!turnOff.IsFailureCap || _failedComparisonsInRow >= FailedComparisonLimit);
}
}

private SyncTurnOff? CountFailureLocked()
{
_failedComparisonsInRow++;
return _failedComparisonsInRow >= FailedComparisonLimit
? new SyncTurnOff(_syncPeriod, new ComparisonReadsFailedError(), IsFailureCap: true)
: null;
}

private void InvalidateLocked()
{
_currentComparisonId = 0;
_isComparisonRunning = false;
_offer = null;
}
}
10 changes: 10 additions & 0 deletions SemiStep/SemiStep.Core/Plc/PlcConflictAnswer.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
namespace SemiStep.Core.Plc;

/// <summary>The operator's answer to a recipe conflict, or the reason none came.</summary>
public enum PlcConflictAnswer
{
KeepLocal,
TakePlc,
Dismissed,
DialogShowFailed
}
Loading