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
3 changes: 3 additions & 0 deletions SemiStep/SemiStep.Core/Plc/IPlcSyncService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ public interface IPlcSyncService
/// <summary>Ends the write pause and drops the recipe notified during it: the PLC already holds the screen recipe.</summary>
void EndWritePauseWithoutWrite();

/// <summary>The PLC holds the screen recipe: sets the status to Synced, which clears the latch of a failed write.</summary>
void ConfirmInSync();

/// <summary>
/// Completes when the attempt in flight at the call has ended; throws when <paramref name="ct"/> cancels first.
/// </summary>
Expand Down
164 changes: 144 additions & 20 deletions SemiStep/SemiStep.Core/Plc/PlcComparisonAnswers.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,28 +2,36 @@

using Microsoft.Extensions.Logging;

using SemiStep.Core.Plc.S7.Serialization;
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.
/// Answers to the offer a comparison made: the conflict answers, the conflict take and the reconnect take. Each
/// decision runs on the UI thread and counts only while its comparison is current. Both takes load through
/// <see cref="TakeLocked"/>, the one place that replaces the session recipe from the PLC.
/// </summary>
internal sealed class PlcComparisonAnswers(
RecipeSession session,
IS7Connection connection,
IS7Reader reader,
IPlcSyncService syncService,
PlcComparisonState state,
PlcSyncSwitch syncSwitch,
PlcConflictNotifier conflictNotifier,
RecipeConverter recipeConverter,
ILogger logger)
{
private readonly RecipeSession _session = session;
private readonly IS7Connection _connection = connection;
private readonly IS7Reader _reader = reader;
private readonly IPlcSyncService _syncService = syncService;
private readonly PlcComparisonState _state = state;
private readonly PlcSyncSwitch _syncSwitch = syncSwitch;
private readonly PlcConflictNotifier _conflictNotifier = conflictNotifier;
private readonly RecipeConverter _recipeConverter = recipeConverter;
private readonly ILogger _logger = logger;

/// <summary>
Expand Down Expand Up @@ -63,8 +71,8 @@ public Result<bool> ApplyRecipeFromPlc(Recipe recipe)
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)
/// <summary>An answer to a stale conflict changes nothing.</summary>
public void ResolveConflict(long comparisonId, PlcConflictAnswer answer)
{
if (!Enum.IsDefined(answer))
{
Expand All @@ -73,31 +81,146 @@ public Result<bool> ResolveConflict(long comparisonId, PlcConflictAnswer answer)

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

if (answer == PlcConflictAnswer.KeepLocal)
{
_syncService.EndWritePause(_session.Current, _session.IsValid);
return;
}

switch (answer)
_syncSwitch.PostTurnOff(_state.TurnOffLocked(
new ConflictUnresolvedError(answer == PlcConflictAnswer.DialogShowFailed)));
}
}

/// <summary>
/// Reads the PLC recipe again for a conflict take and decides nothing. A recipe that is not committed reads as
/// empty; a failure or a throw reads as a failed result.
/// </summary>
public async Task<Result<Recipe>> ReadForTakeAsync(CancellationToken ct)
{
try
{
var managingArea = await _reader.ReadManagingAreaAsync(ct);
if (managingArea.IsFailed)
{
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");
return managingArea.ToResult<Recipe>();
}

return managingArea.Value.Committed ? await _reader.ReadRecipeFromPlcAsync(ct) : Result.Ok(Recipe.Empty);
}
catch (OperationCanceledException ex)
{
_logger.LogInformation("Reading the PLC recipe for the conflict take was cancelled");
return Result.Fail<Recipe>(new ExceptionalError(ex));
}
catch (Exception ex)
{
_logger.LogWarning(ex, "Reading the PLC recipe for the conflict take threw");
return Result.Fail<Recipe>(new ExceptionalError(ex));
}
}

/// <summary>False once a link drop, a newer comparison or sync off made the conflict stale, or it ended.</summary>
public bool IsConflictCurrent(long comparisonId)
{
lock (_state.Gate)
{
return _state.HasOfferLocked(offer => offer.IsConflict && offer.ComparisonId == comparisonId);
}
}

/// <summary>The load notifies sync while the pause holds, so ending the pause next drops that recipe.</summary>
/// <summary>
/// Ends the conflict with the recipe <see cref="ReadForTakeAsync"/> returned, unless the screen changed since the
/// operator agreed to drop <paramref name="screenRecipe"/>. A failed read fails, also for a stale conflict.
/// </summary>
public Result<PlcTakeOutcome> TakeConflictRecipe(long comparisonId, Recipe screenRecipe, Result<Recipe> read)
{
bool isLinkLossDue;
Result<PlcTakeOutcome> result;
lock (_state.Gate)
{
result = DecideTakeLocked(comparisonId, screenRecipe, read, out isLinkLossDue);
}

if (isLinkLossDue)
{
_connection.DeclareLinkLost();
}

return result;
}

private Result<PlcTakeOutcome> DecideTakeLocked(
long comparisonId,
Recipe screenRecipe,
Result<Recipe> read,
out bool isLinkLossDue)
{
isLinkLossDue = false;
bool IsThisConflict(PlcRecipeOffer offer)
{
return offer.IsConflict && offer.ComparisonId == comparisonId;
}

if (!_state.HasOfferLocked(IsThisConflict))
{
_logger.LogInformation("PLC conflict take ignored: its comparison is stale");
return read.IsFailed ? ReadFailed(read, isLinkLossDeclared: false) : Result.Ok(PlcTakeOutcome.NotReplaced);
}

if (read.IsFailed)
{
_state.TakeOfferLocked(IsThisConflict);
isLinkLossDue = true;
return ReadFailed(read, isLinkLossDeclared: true);
}

var plcRecipe = read.Value;
if (plcRecipe.Steps.Count == 0)
{
_state.TakeOfferLocked(IsThisConflict);
_syncService.EndWritePause(_session.Current, _session.IsValid);
return Result.Ok(PlcTakeOutcome.NotReplaced).WithSuccess(new PlcRecipeAbsentWarning());
}

if (PlcRecipeDataComparer.EncodesToSamePlcData(_recipeConverter, _session.Current, plcRecipe, _logger))
{
_state.TakeOfferLocked(IsThisConflict);
_syncService.EndWritePauseWithoutWrite();
_syncService.ConfirmInSync();
return Result.Ok(PlcTakeOutcome.NotReplaced);
}

if (!ReferenceEquals(_session.Current, screenRecipe))
{
return Result.Ok(PlcTakeOutcome.ScreenChanged);
}

_state.TakeOfferLocked(IsThisConflict);
var takeResult = TakeLocked(plcRecipe);
return takeResult.IsFailed
? takeResult.ToResult<PlcTakeOutcome>()
: Result.Ok(PlcTakeOutcome.Replaced).WithReasons(takeResult.Reasons);
}

private Result<PlcTakeOutcome> ReadFailed(Result<Recipe> read, bool isLinkLossDeclared)
{
_logger.LogWarning(
"Could not read the PLC recipe for the conflict take: {Errors}",
string.Join("; ", read.Errors.Select(e => e.Message)));
return Result.Fail<PlcTakeOutcome>(new PlcTakeReadFailedError(isLinkLossDeclared).CausedBy(read.Errors));
}

/// <summary>
/// The load notifies sync while the pause holds, so ending the pause next drops that recipe; the PLC holds the
/// screen recipe then.
/// </summary>
private Result<bool> TakeLocked(Recipe plcRecipe)
{
Result loadResult;
Expand All @@ -118,6 +241,7 @@ private Result<bool> TakeLocked(Recipe plcRecipe)
}

_syncService.EndWritePauseWithoutWrite();
_syncService.ConfirmInSync();
return Result.Ok(true).WithReasons(loadResult.Reasons);
}
}
7 changes: 6 additions & 1 deletion SemiStep/SemiStep.Core/Plc/PlcComparisonState.cs
Original file line number Diff line number Diff line change
Expand Up @@ -191,10 +191,15 @@ public bool WasTakeConvertedToConflict(long comparisonId)
}
}

public bool HasOfferLocked(Func<PlcRecipeOffer, bool> matches)
{
return _offer is { } offer && IsCurrentLocked(offer.ComparisonId) && matches(offer);
}

/// <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))
if (_offer is not { } offer || !HasOfferLocked(matches))
{
return null;
}
Expand Down
6 changes: 4 additions & 2 deletions SemiStep/SemiStep.Core/Plc/PlcConflictAnswer.cs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
namespace SemiStep.Core.Plc;

/// <summary>The operator's answer to a recipe conflict, or the reason none came.</summary>
/// <summary>
/// The operator's answer to a recipe conflict, or the reason none came. Taking the PLC recipe is
/// <see cref="PlcLifecycleManager.TakeConflictRecipe"/>, which reads the PLC again first.
/// </summary>
public enum PlcConflictAnswer
{
KeepLocal,
TakePlc,
Dismissed,
DialogShowFailed
}
32 changes: 27 additions & 5 deletions SemiStep/SemiStep.Core/Plc/PlcLifecycleManager.cs
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,7 @@ public PlcLifecycleManager(
_logger = logger;

var lifetime = _lifetimeCts.Token;
var recipeConverter = new RecipeConverter(recipeMetadataRegistry);
_syncSwitch = new PlcSyncSwitch(
connection,
reader,
Expand All @@ -74,15 +75,18 @@ public PlcLifecycleManager(
_syncSwitch,
_conflictNotifier,
_reconnectTake,
new RecipeConverter(recipeMetadataRegistry),
recipeConverter,
logger,
lifetime);
_answers = new PlcComparisonAnswers(
session,
connection,
reader,
syncService,
_comparisonState,
_syncSwitch,
_conflictNotifier,
recipeConverter,
logger);
}

Expand Down Expand Up @@ -187,13 +191,31 @@ public void RegisterReconnectApplyCallback(Func<Recipe, Task<Result>> callback)
_reconnectTake.RegisterApplyCallback(callback);
}

/// <summary>Ends the conflict of <paramref name="comparisonId"/>; an answer to a stale conflict changes nothing.</summary>
public void ResolveConflict(long comparisonId, PlcConflictAnswer answer)
{
_answers.ResolveConflict(comparisonId, answer);
}

/// <summary>False once a link drop, a newer comparison or sync off made the conflict stale, or it ended.</summary>
public bool IsConflictCurrent(long comparisonId)
{
return _answers.IsConflictCurrent(comparisonId);
}

/// <summary>Reads the PLC recipe again for a conflict take; a recipe that is not committed reads as empty.</summary>
public Task<Result<Recipe>> ReadRecipeForTakeAsync(CancellationToken ct)
{
return _answers.ReadForTakeAsync(ct);
}

/// <summary>
/// Ends the conflict of <paramref name="comparisonId"/>. Returns whether the session recipe was replaced; an
/// answer to a stale conflict changes nothing.
/// Ends the conflict of <paramref name="comparisonId"/> with the recipe <see cref="ReadRecipeForTakeAsync"/>
/// returned: takes it, writes the screen recipe when the PLC holds none, or declares link loss on a failed read.
/// </summary>
public Result<bool> ResolveConflict(long comparisonId, PlcConflictAnswer answer)
public Result<PlcTakeOutcome> TakeConflictRecipe(long comparisonId, Recipe screenRecipe, Result<Recipe> read)
{
return _answers.ResolveConflict(comparisonId, answer);
return _answers.TakeConflictRecipe(comparisonId, screenRecipe, read);
}

private void OnConnectionStateChanged(PlcConnectionState state)
Expand Down
14 changes: 14 additions & 0 deletions SemiStep/SemiStep.Core/Plc/PlcTakeOutcome.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
namespace SemiStep.Core.Plc;

/// <summary>How a take of the conflict's PLC recipe ended.</summary>
public enum PlcTakeOutcome
{
/// <summary>The PLC recipe replaced the screen recipe.</summary>
Replaced,

/// <summary>The conflict ended, or was already stale, and the screen recipe stayed.</summary>
NotReplaced,

/// <summary>The screen recipe changed after the operator chose; the offer stays for a new answer.</summary>
ScreenChanged
}
8 changes: 8 additions & 0 deletions SemiStep/SemiStep.Core/Plc/Sync/PlcRecipeAbsentWarning.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
using SemiStep.Core.Shared;

namespace SemiStep.Core.Plc.Sync;

/// <summary>The PLC recipe the operator chose to take was gone by the take, so the screen recipe was written.</summary>
public sealed class PlcRecipeAbsentWarning() : Warning("The PLC holds no recipe. The screen recipe was written.")
{
}
10 changes: 10 additions & 0 deletions SemiStep/SemiStep.Core/Plc/Sync/PlcSyncCoordinator.cs
Original file line number Diff line number Diff line change
Expand Up @@ -195,6 +195,16 @@ public void EndWritePauseWithoutWrite()
});
}

/// <summary>The PLC holds the screen recipe, warnings included, so nothing is left unwritten.</summary>
public void ConfirmInSync()
{
Transition(() =>
{
_isLatestRecipeValid = true;
return new TransitionResult(SetStatusLocked(PlcSyncStatus.Synced), null, null);
});
}

public void UpdateConnectionState(PlcConnectionState state)
{
Transition(() =>
Expand Down
10 changes: 10 additions & 0 deletions SemiStep/SemiStep.Core/Plc/Sync/PlcTakeReadFailedError.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
using FluentResults;

namespace SemiStep.Core.Plc.Sync;

/// <summary>The read of the PLC recipe for a conflict take failed or passed its bound; nothing was taken.</summary>
public sealed class PlcTakeReadFailedError(bool isLinkLossDeclared) : Error("Could not read the recipe from the PLC.")
{
/// <summary>The conflict was still current, so the failed read declared link loss and a link-loss fault follows.</summary>
public bool IsLinkLossDeclared { get; } = isLinkLossDeclared;
}
Original file line number Diff line number Diff line change
Expand Up @@ -555,7 +555,7 @@ public async Task ResolveConflict_TakePlcRecipeFailingImportCheck_LeavesSessionU
}

/// <summary>Raises a conflict over a saved local recipe with undo history, then takes the PLC recipe.</summary>
private static async Task<Result<bool>> TakeConflictingPlcRecipeAsync(
private static async Task<Result<PlcTakeOutcome>> TakeConflictingPlcRecipeAsync(
PlcLifecycleManager plc,
RecipeSession session,
StubS7Service s7Service,
Expand All @@ -570,7 +570,7 @@ private static async Task<Result<bool>> TakeConflictingPlcRecipeAsync(
conflict.Should().NotBeNull();
var notificationsBefore = syncService.NotifyRecipeChangedCallCount;

var result = plc.ResolveConflict(conflict.ComparisonId, PlcConflictAnswer.TakePlc);
var result = plc.TakeConflictRecipe(conflict.ComparisonId, session.Current, Result.Ok(conflict.Plc));

result.IsFailed.Should().BeTrue();
session.Snapshot.Should().BeSameAs(snapshotBefore);
Expand Down
Loading