diff --git a/App.xaml.cs b/App.xaml.cs index 7a0d16197..51a039ebb 100644 --- a/App.xaml.cs +++ b/App.xaml.cs @@ -6,6 +6,7 @@ using System.Windows; using System.Windows.Controls; using System.Windows.Threading; +using ArIED61850Tester.Services; namespace ArIED61850Tester; @@ -22,6 +23,20 @@ protected override void OnStartup(StartupEventArgs e) WindowsApplicationIdentity.Apply(); base.OnStartup(e); + if (SclSafeTrialCommand.IsRequested(e.Args)) + { + var trial = SclSafeTrialRunner.RunAsync(e.Args, CancellationToken.None) + .GetAwaiter() + .GetResult(); + MessageBox.Show( + $"{trial.Message}\n\nEvidence: {trial.EvidencePath}", + trial.IsSuccess ? "SCL Safe Trial — PASS" : "SCL Safe Trial — NOT PROVEN", + MessageBoxButton.OK, + trial.IsSuccess ? MessageBoxImage.Information : MessageBoxImage.Warning); + Shutdown(trial.ExitCode); + return; + } + // P2 installs one calm industrial visual system before StartupUri materializes. // Existing XAML keeps its semantic resource keys while the overlay replaces // glare-heavy white/blue surfaces with Blue Steel + Light Greige equivalents. @@ -64,6 +79,12 @@ protected override void OnActivated(EventArgs e) // tiny P2 adapter when windows activate so newly opened FAT workspaces also // inherit the selected industrial theme without touching engine workflows. P2BlueSteelGreigeUx.ApplyToOpenWindows(this); + + // Keep onboarding task-first while preserving the existing protocol handlers: + // Add IED exposes SCL/CID/ICD or IP discovery, and bulk connect appears only + // when multiple loaded IEDs make the action useful. The behavior is dispatcher-safe. + if (Current?.MainWindow is MainWindow mainWindow) + SmartIedOnboardingBehavior.Install(mainWindow); } private void InstallP2BlueSteelGreigeTheme() diff --git a/ControlCommandWindow.xaml.cs b/ControlCommandWindow.xaml.cs index 23d9014ee..d9769afa5 100644 --- a/ControlCommandWindow.xaml.cs +++ b/ControlCommandWindow.xaml.cs @@ -187,10 +187,12 @@ private async void SendCommand_Click(object sender, RoutedEventArgs e) }, _cancellation.Token); - CommandStage = result.Stage; + CommandStage = result.IsSuccess && !TestMode ? "Command accepted" : result.Stage; CommandStatus = BuildCommandResultText(result); - if (!string.IsNullOrWhiteSpace(result.FeedbackValue) && result.FeedbackValue != "-") - CurrentValue = result.FeedbackValue; + if (result.IsSuccess && !TestMode) + { + CommandStatus += " Command accepted by the IEC 61850 control service. Waiting for independent IED process feedback; monitored stVal is not changed from the command path."; + } SetResultTone(result.IsSuccess ? "Success" : "Error"); } catch (OperationCanceledException) @@ -312,7 +314,7 @@ private static string BuildCommandResultText(Iec61850ControlCommandResult result if (!string.IsNullOrWhiteSpace(result.ElapsedText) && result.ElapsedText != "-") details.Add($"Control service: {result.ElapsedText}."); if (!string.IsNullOrWhiteSpace(result.FeedbackElapsedText) && result.FeedbackElapsedText != "-") - details.Add($"Process feedback: {result.FeedbackElapsedText}."); + details.Add($"Control-side feedback verification: {result.FeedbackElapsedText}. This does not overwrite monitored stVal."); if (!string.IsNullOrWhiteSpace(result.TotalElapsedText) && result.TotalElapsedText != "-") details.Add($"Total: {result.TotalElapsedText}."); return string.Join(" ", details.Where(text => !string.IsNullOrWhiteSpace(text))); diff --git a/Controls/ComtradeHarmonicsWorkstationView.cs b/Controls/ComtradeHarmonicsWorkstationView.cs index 17fe7bfa4..73580609a 100644 --- a/Controls/ComtradeHarmonicsWorkstationView.cs +++ b/Controls/ComtradeHarmonicsWorkstationView.cs @@ -1,3 +1,4 @@ +using System.Diagnostics; using System.Globalization; using System.Windows; using System.Windows.Input; @@ -65,7 +66,10 @@ public sealed class ComtradeHarmonicsWorkstationView : FrameworkElement private static readonly Pen FooterDividerPen = FreezePen(Color.FromRgb(233, 237, 243), 1); private static readonly string[] OrderLabels = CreateOrderLabels(); + private const double PresentationTimeConstantMs = 92.0; private IReadOnlyList _spectra = Array.Empty(); + private ComtradeHarmonicOverviewSpectrum[] _smoothedSpectra = Array.Empty(); + private long _lastPresentationTimestamp; private PreparedSpectrumRow[] _preparedRows = Array.Empty(); private int _maximumDisplayedOrder = -1; private string _title = "Harmonics"; @@ -105,7 +109,14 @@ internal void ShowSpectra( { _title = title ?? string.Empty; _subtitle = subtitle ?? string.Empty; - _spectra = spectra ?? Array.Empty(); + var targetSpectra = spectra ?? Array.Empty(); + var now = Stopwatch.GetTimestamp(); + var elapsedMilliseconds = _lastPresentationTimestamp == 0 + ? double.PositiveInfinity + : Stopwatch.GetElapsedTime(_lastPresentationTimestamp, now).TotalMilliseconds; + _lastPresentationTimestamp = now; + _smoothedSpectra = SmoothSpectra(_smoothedSpectra, targetSpectra, elapsedMilliseconds); + _spectra = _smoothedSpectra; _maximumDisplayedOrder = ResolveMaximumDisplayedOrder(_spectra); _selectedOrder = Math.Clamp(_selectedOrder, 0, Math.Max(0, _maximumDisplayedOrder)); _preparedRows = PrepareRows(_spectra, _maximumDisplayedOrder); @@ -118,6 +129,8 @@ internal void ShowMessage(string title, string message) _title = title ?? string.Empty; _subtitle = message ?? string.Empty; _spectra = Array.Empty(); + _smoothedSpectra = Array.Empty(); + _lastPresentationTimestamp = 0; _preparedRows = Array.Empty(); _maximumDisplayedOrder = -1; _rowTargets.Clear(); @@ -296,6 +309,79 @@ private void DrawFooter(DrawingContext dc, Rect bounds, double dpi) FooterRateBrush, new Point(bounds.Right - 16, y), dpi); } + private static ComtradeHarmonicOverviewSpectrum[] SmoothSpectra( + IReadOnlyList previous, + IReadOnlyList target, + double elapsedMilliseconds) + { + if (target.Count == 0) + return Array.Empty(); + + var topologyMatches = previous.Count == target.Count && previous.Count > 0; + if (topologyMatches) + { + for (var spectrumIndex = 0; spectrumIndex < target.Count; spectrumIndex++) + { + var before = previous[spectrumIndex]; + var next = target[spectrumIndex]; + if (!string.Equals(before.SignalName, next.SignalName, StringComparison.Ordinal) || + !string.Equals(before.Units, next.Units, StringComparison.Ordinal) || + before.Bins.Count != next.Bins.Count) + { + topologyMatches = false; + break; + } + for (var binIndex = 0; binIndex < next.Bins.Count; binIndex++) + { + if (before.Bins[binIndex].Order != next.Bins[binIndex].Order) + { + topologyMatches = false; + break; + } + } + if (!topologyMatches) break; + } + } + + var result = new ComtradeHarmonicOverviewSpectrum[target.Count]; + for (var spectrumIndex = 0; spectrumIndex < target.Count; spectrumIndex++) + { + var next = target[spectrumIndex]; + if (!topologyMatches) + { + result[spectrumIndex] = next with { Bins = next.Bins.ToArray() }; + continue; // First sample/channel-set change snaps; never invent a ramp from zero. + } + + var before = previous[spectrumIndex]; + var bins = new ComtradeHarmonicDisplayBin[next.Bins.Count]; + for (var binIndex = 0; binIndex < bins.Length; binIndex++) + { + var previousBin = before.Bins[binIndex]; + var targetBin = next.Bins[binIndex]; + bins[binIndex] = new ComtradeHarmonicDisplayBin( + targetBin.Order, + PresentationEasingMath.Smooth(previousBin.MagnitudeRms, targetBin.MagnitudeRms, elapsedMilliseconds, PresentationTimeConstantMs), + PresentationEasingMath.Smooth(previousBin.PercentOfFundamental, targetBin.PercentOfFundamental, elapsedMilliseconds, PresentationTimeConstantMs), + PresentationEasingMath.SmoothAngleDegrees(previousBin.AngleDegrees, targetBin.AngleDegrees, elapsedMilliseconds, PresentationTimeConstantMs)); + } + + result[spectrumIndex] = new ComtradeHarmonicOverviewSpectrum( + next.SignalName, + next.Units, + PresentationEasingMath.Smooth(before.DcComponent, next.DcComponent, elapsedMilliseconds, PresentationTimeConstantMs), + PresentationEasingMath.Smooth(before.FundamentalRms, next.FundamentalRms, elapsedMilliseconds, PresentationTimeConstantMs), + PresentationEasingMath.Smooth(before.ThdPercent, next.ThdPercent, elapsedMilliseconds, PresentationTimeConstantMs), + next.DominantOrder, + PresentationEasingMath.Smooth(before.DominantRms, next.DominantRms, elapsedMilliseconds, PresentationTimeConstantMs), + PresentationEasingMath.Smooth(before.DominantPercent, next.DominantPercent, elapsedMilliseconds, PresentationTimeConstantMs), + next.EstimatedSampleRateHz, + next.MaximumResolvableOrder, + bins); + } + return result; + } + private static PreparedSpectrumRow[] PrepareRows( IReadOnlyList spectra, int maximumOrder) diff --git a/Controls/ComtradePhasorView.cs b/Controls/ComtradePhasorView.cs index 369d105dd..9564c3081 100644 --- a/Controls/ComtradePhasorView.cs +++ b/Controls/ComtradePhasorView.cs @@ -1,6 +1,8 @@ +using System.Diagnostics; using System.Globalization; using System.Windows; using System.Windows.Media; +using ArIED61850Tester.Services; namespace ArIED61850Tester.Controls; @@ -34,9 +36,13 @@ public sealed class ComtradePhasorView : FrameworkElement private PreparedPhasorPanel _voltagePanel = PreparedPhasorPanel.Empty; private PreparedPhasorPanel _currentPanel = PreparedPhasorPanel.Empty; + private const double PresentationTimeConstantMs = 78.0; private string _headerLabel = "Fundamental phasors at C1"; private string _referenceDetail = "Select a valid analysis reference"; private string _message = string.Empty; + private ComtradePhasorVector[] _smoothedVoltageVectors = Array.Empty(); + private ComtradePhasorVector[] _smoothedCurrentVectors = Array.Empty(); + private long _lastPresentationTimestamp; internal void ShowPhasors( string referenceLabel, @@ -47,8 +53,17 @@ internal void ShowPhasors( var resolvedReference = string.IsNullOrWhiteSpace(referenceLabel) ? "Reference" : referenceLabel; _headerLabel = $"Fundamental phasors at {resolvedReference}"; _referenceDetail = referenceDetail ?? string.Empty; - _voltagePanel = PreparePanel(voltageVectors); - _currentPanel = PreparePanel(currentVectors); + + var now = Stopwatch.GetTimestamp(); + var elapsedMilliseconds = _lastPresentationTimestamp == 0 + ? double.PositiveInfinity + : Stopwatch.GetElapsedTime(_lastPresentationTimestamp, now).TotalMilliseconds; + _lastPresentationTimestamp = now; + + _smoothedVoltageVectors = SmoothVectors(_smoothedVoltageVectors, voltageVectors, elapsedMilliseconds); + _smoothedCurrentVectors = SmoothVectors(_smoothedCurrentVectors, currentVectors, elapsedMilliseconds); + _voltagePanel = PreparePanel(_smoothedVoltageVectors); + _currentPanel = PreparePanel(_smoothedCurrentVectors); _message = string.Empty; InvalidateVisual(); } @@ -60,6 +75,9 @@ internal void ShowMessage(string title, string message) _referenceDetail = message ?? string.Empty; _voltagePanel = PreparedPhasorPanel.Empty; _currentPanel = PreparedPhasorPanel.Empty; + _smoothedVoltageVectors = Array.Empty(); + _smoothedCurrentVectors = Array.Empty(); + _lastPresentationTimestamp = 0; _message = message ?? string.Empty; InvalidateVisual(); } @@ -111,6 +129,51 @@ protected override void OnRender(DrawingContext dc) } } + private static ComtradePhasorVector[] SmoothVectors( + IReadOnlyList previous, + IReadOnlyList? target, + double elapsedMilliseconds) + { + if (target is null || target.Count == 0) + return Array.Empty(); + + var topologyMatches = previous.Count == target.Count && previous.Count > 0; + if (topologyMatches) + { + for (var index = 0; index < target.Count; index++) + { + if (!string.Equals(previous[index].Label, target[index].Label, StringComparison.Ordinal) || + !string.Equals(previous[index].Phase, target[index].Phase, StringComparison.Ordinal) || + !string.Equals(previous[index].Units, target[index].Units, StringComparison.Ordinal)) + { + topologyMatches = false; + break; + } + } + } + + var output = new ComtradePhasorVector[target.Count]; + if (!topologyMatches) + { + for (var index = 0; index < target.Count; index++) + output[index] = target[index]; + return output; // First sample/topology change snaps: no artificial ramp from zero. + } + + for (var index = 0; index < target.Count; index++) + { + var before = previous[index]; + var next = target[index]; + output[index] = new ComtradePhasorVector( + next.Label, + next.Phase, + next.Units, + PresentationEasingMath.Smooth(before.MagnitudeRms, next.MagnitudeRms, elapsedMilliseconds, PresentationTimeConstantMs), + PresentationEasingMath.SmoothAngleDegrees(before.AngleDegrees, next.AngleDegrees, elapsedMilliseconds, PresentationTimeConstantMs)); + } + return output; + } + private static PreparedPhasorPanel PreparePanel(IReadOnlyList? source) { if (source is null || source.Count == 0) diff --git a/Services/Iec61850ConnectionPathPolicy.cs b/Services/Iec61850ConnectionPathPolicy.cs new file mode 100644 index 000000000..dc3f9281f --- /dev/null +++ b/Services/Iec61850ConnectionPathPolicy.cs @@ -0,0 +1,29 @@ +using ArIED61850Tester.Models; + +namespace ArIED61850Tester.Services; + +public enum Iec61850ConnectionPath +{ + FullDiscovery, + CachedLiveModel, + SclAssisted +} + +/// +/// Pure routing policy. SCL design authority is distinct from a saved live-discovery +/// cache: Play/Connect uses the SCL-assisted path, while Re-scan remains an explicit +/// caller of full discovery. +/// +public static class Iec61850ConnectionPathPolicy +{ + public static Iec61850ConnectionPath SelectForFastConnect(Iec61850MonitorDevice device) + { + ArgumentNullException.ThrowIfNull(device); + + if (device.HasSclDesignModel) + return Iec61850ConnectionPath.SclAssisted; + if (device.HasDiscoveryCache && device.Signals.Count > 0) + return Iec61850ConnectionPath.CachedLiveModel; + return Iec61850ConnectionPath.FullDiscovery; + } +} diff --git a/Services/Iec61850MonitorRuntime.cs b/Services/Iec61850MonitorRuntime.cs index 0b939ec05..d9ed9af87 100644 --- a/Services/Iec61850MonitorRuntime.cs +++ b/Services/Iec61850MonitorRuntime.cs @@ -31,13 +31,6 @@ private sealed class RuntimePointState public bool ReportChangeVerified { get; set; } public DateTime LastReportUtc { get; set; } = DateTime.MinValue; public bool ReportMissLogged { get; set; } - public string CommandFeedbackValue { get; set; } = string.Empty; - public DateTime LastCommandFeedbackUtc { get; set; } = DateTime.MinValue; - public DateTime CommandFeedbackGuardUntilUtc { get; set; } = DateTime.MinValue; - public DateTime CommandReportDeadlineUtc { get; set; } = DateTime.MinValue; - public bool AwaitingCommandReportEdge { get; set; } - public bool CommandReportMissLogged { get; set; } - public bool StaleReportSuppressedLogged { get; set; } public bool ReportValueRejectedLogged { get; set; } public string LastLoggedDegradedQuality { get; set; } = string.Empty; public int ConsecutiveErrors { get; set; } @@ -258,12 +251,19 @@ public async Task ConnectUsingCachedModelAsync( { ArgumentNullException.ThrowIfNull(device); ValidateEndpoint(device); - if (!device.HasDiscoveryCache || device.Signals.Count == 0) + + var connectionPath = Iec61850ConnectionPathPolicy.SelectForFastConnect(device); + if (connectionPath == Iec61850ConnectionPath.FullDiscovery) + throw new InvalidOperationException($"{device.Name} has no trusted SCL design or successful saved discovery model. Run a full discovery first."); + if (connectionPath == Iec61850ConnectionPath.CachedLiveModel && + (!device.HasDiscoveryCache || device.Signals.Count == 0)) throw new InvalidOperationException($"{device.Name} has no successful saved discovery model. Run a full discovery first."); progress?.Report(new IedDiscoveryProgress( IedDiscoveryStage.PreparingSession, - "Preparing saved IEC 61850 model…", + connectionPath == Iec61850ConnectionPath.SclAssisted + ? "Verifying trusted SCL/CID source…" + : "Preparing saved IEC 61850 model…", 4d, 1, 4)); @@ -277,11 +277,20 @@ public async Task ConnectUsingCachedModelAsync( _sessions[device.DeviceId] = session; device.IsConnected = false; - device.LastDiagnosticSnapshot = session.Client.CaptureDiagnosticSnapshot("Preparing fast connection from saved model"); - device.Status = "Fast connecting"; - device.Detail = $"Opening {device.IpAddress}:{device.Port} with the saved discovery model."; + device.LastDiagnosticSnapshot = session.Client.CaptureDiagnosticSnapshot( + connectionPath == Iec61850ConnectionPath.SclAssisted + ? "Preparing verified SCL-assisted connection" + : "Preparing fast connection from saved model"); + device.Status = connectionPath == Iec61850ConnectionPath.SclAssisted + ? "SCL connecting" + : "Fast connecting"; + device.Detail = connectionPath == Iec61850ConnectionPath.SclAssisted + ? $"Opening {device.IpAddress}:{device.Port} with verified SCL association identity." + : $"Opening {device.IpAddress}:{device.Port} with the saved discovery model."; Log("INFO", device.Name, - $"Fast reconnect using saved model ({device.SignalCount:N0} signals); full live discovery is skipped."); + connectionPath == Iec61850ConnectionPath.SclAssisted + ? "Trusted SCL authority selected for Play; source SHA will be verified before any socket is opened and no discovery fallback is allowed." + : $"Fast reconnect using saved model ({device.SignalCount:N0} signals); full live discovery is skipped."); try { @@ -292,7 +301,10 @@ public async Task ConnectUsingCachedModelAsync( 2, 4)); - await ConnectCachedAssociationWithRetryAsync(session, cancellationToken).ConfigureAwait(false); + connectionPath = await ConnectUsingSelectedFastPathAsync( + session, + cancellationToken, + allowCachedRetry: true).ConfigureAwait(false); if (!session.Client.IsConnected) { device.Status = "Connection failed"; @@ -304,32 +316,47 @@ public async Task ConnectUsingCachedModelAsync( progress?.Report(new IedDiscoveryProgress( IedDiscoveryStage.AssociatingMms, - "ACSE/MMS associated. Restoring saved signal workspace…", + connectionPath == Iec61850ConnectionPath.SclAssisted + ? "SCL association validated. Restoring SCL signal workspace…" + : "ACSE/MMS associated. Restoring saved signal workspace…", 74d, 3, 4)); device.IsConnected = true; - device.LastDiagnosticSnapshot = session.Client.CaptureDiagnosticSnapshot("Fast connection complete"); + device.LastDiagnosticSnapshot = session.Client.CaptureDiagnosticSnapshot( + connectionPath == Iec61850ConnectionPath.SclAssisted + ? "Verified SCL-assisted connection complete" + : "Fast connection complete"); device.Status = "Ready"; - device.Detail = $"Connected with saved model: {device.SignalCount:N0} signal(s), {device.SelectedSignalCount:N0} selected. Full discovery was skipped."; - device.AcquisitionMode = "Saved model • ready to monitor"; + device.Detail = connectionPath == Iec61850ConnectionPath.SclAssisted + ? $"Connected from verified SCL: {device.SignalCount:N0} signal(s), {device.SelectedSignalCount:N0} selected. Domain/VMD validation and bounded FC-root reads completed; full discovery was skipped." + : $"Connected with saved model: {device.SignalCount:N0} signal(s), {device.SelectedSignalCount:N0} selected. Full discovery was skipped."; + device.AcquisitionMode = connectionPath == Iec61850ConnectionPath.SclAssisted + ? "Verified SCL • ready to monitor" + : "Saved model • ready to monitor"; device.RefreshComputed(); progress?.Report(new IedDiscoveryProgress( IedDiscoveryStage.Complete, - "Saved model restored — ready for live values.", + connectionPath == Iec61850ConnectionPath.SclAssisted + ? "Verified SCL online path ready for static reporting." + : "Saved model restored — ready for live values.", 100d, 4, 4)); Log("INFO", device.Name, - "Fast reconnect complete. Reporting setup will validate only the acquisition objects required by the selected points; the full signal scan remains cached."); + connectionPath == Iec61850ConnectionPath.SclAssisted + ? "Trusted SCL connection complete. Static reporting will reuse SCL RCB/DataSet authority; no network DataSet-directory browse, dynamic DataSet mutation, or implicit GI is permitted." + : "Fast reconnect complete. Reporting setup will validate only the acquisition objects required by the selected points; the full signal scan remains cached."); } catch (Exception ex) { device.LastDiagnosticSnapshot = session.Client.CaptureDiagnosticSnapshot( - "Fast TCP/ACSE/MMS connection failed", + connectionPath == Iec61850ConnectionPath.SclAssisted + ? "Verified SCL-assisted connection failed" + : "Fast TCP/ACSE/MMS connection failed", ex); if (!session.Client.IsConnected) { @@ -349,6 +376,45 @@ await DisposeClientForReconnectAsync( } } + private async Task ConnectUsingSelectedFastPathAsync( + DeviceSession session, + CancellationToken cancellationToken, + bool allowCachedRetry) + { + var device = session.Device; + var path = Iec61850ConnectionPathPolicy.SelectForFastConnect(device); + if (path == Iec61850ConnectionPath.FullDiscovery) + throw new InvalidOperationException($"{device.Name} requires full discovery; fast-connect cannot invent a model authority."); + + if (path == Iec61850ConnectionPath.SclAssisted) + { + var verified = await VerifiedSclSourceLoader.LoadAsync( + device.SclSourcePath, + device.SclSourceSha256, + cancellationToken).ConfigureAwait(false); + var result = await session.Client.ConnectUsingSclAsync( + verified.Xml, + device.SclIedName, + device.SclAccessPointName, + device.IpAddress, + device.Port, + cancellationToken).ConfigureAwait(false); + if (!result.IsSuccess || !session.Client.IsConnected) + throw new InvalidOperationException(result.Message); + + device.LiveDiscoveryModel = session.Client.LastLiveModel ?? device.SclWorkspace?.DesignModel; + Log("INFO", device.Name, + $"Verified SCL authority active: SHA256={verified.Sha256}; IED={device.SclIedName}; AP={device.SclAccessPointName}; maxReadRefs={result.Preparation.InitialReadPlan?.MaximumVariableReferencesPerRead ?? 0}."); + return path; + } + + if (allowCachedRetry) + await ConnectCachedAssociationWithRetryAsync(session, cancellationToken).ConfigureAwait(false); + else + await session.Client.ConnectAsync(device.IpAddress, device.Port, cancellationToken).ConfigureAwait(false); + return path; + } + public async Task> StartMonitoringAsync( Iec61850MonitorDevice device, IEnumerable selectedSignals, @@ -536,8 +602,10 @@ public async Task ExecuteControlAsync( if (result.ServiceAccepted || result.FeedbackConfirmed || result.IsSuccess) RecordSuccessfulIo(session); - if (!request.TestMode && result.FeedbackConfirmed && !string.IsNullOrWhiteSpace(result.FeedbackValue) && result.FeedbackValue != "-") - ApplyControlFeedbackToMonitor(session, request.Signal, result.FeedbackValue); + // IMPORTANT: a successful/confirmed IEC 61850 control service is command-path evidence, + // not process-image authority. Never synthesize or inject stVal from Operate/SBO feedback here. + // The monitored state changes only through the independent acquisition path (RCB/report or + // an explicit authoritative MMS read performed by the monitor), matching IED engineering tools. var wireState = result.CompletionState.Equals("NotSent", StringComparison.OrdinalIgnoreCase) ? "NOT SENT TO IED" @@ -611,50 +679,6 @@ public async Task ExecuteControlAsync( return result; } - private void ApplyControlFeedbackToMonitor(DeviceSession session, SignalDefinition signal, string feedbackValue) - { - var references = BuildControlFeedbackReferences(signal); - var point = FindPointForControlFeedback(session, references); - if (point == null || !session.States.TryGetValue(point.PointKey, out var state)) - { - Log("WARN", session.Device.Name, - $"Control feedback {feedbackValue} was confirmed by the IED, but no monitored status point matched {string.Join(", ", references)}. Live Monitor was not updated directly."); - return; - } - - var nowUtc = DateTime.UtcNow; - var display = Iec61850ValueFormatter.Format(feedbackValue, point.IecDataType, point.Unit); - state.CommandFeedbackValue = display; - state.LastCommandFeedbackUtc = nowUtc; - state.CommandFeedbackGuardUntilUtc = nowUtc.AddSeconds(2); - state.CommandReportDeadlineUtc = nowUtc.AddSeconds(2); - state.AwaitingCommandReportEdge = session.PointPlanIds.ContainsKey(point.PointKey); - state.CommandReportMissLogged = false; - state.StaleReportSuppressedLogged = false; - if (state.AwaitingCommandReportEdge) - state.ReportChangeVerified = false; - - var sourceMode = string.IsNullOrWhiteSpace(state.AcquisitionLabel) - ? "Control feedback" - : state.AcquisitionLabel; - ApplyValueUpdate( - session, - point, - display, - state.Quality, - state.DeviceTimestamp, - sourceMode, - "confirmed command feedback / awaiting matching dchg", - nowUtc, - state.AwaitingCommandReportEdge - ? "Live / command feedback immediate, awaiting report edge" - : "Live / control feedback confirmed", - trustReportEdge: false); - - Log("INFO", session.Device.Name, - $"Live Monitor feedback injected immediately: {point.IecReference}={display}; reportCorrelation={(state.AwaitingCommandReportEdge ? "awaiting dchg" : "not report-assigned")}."); - } - public HybridReportPhysicalValidationSnapshot CaptureHybridReportPhysicalValidation(string deviceId) { ArgumentException.ThrowIfNullOrWhiteSpace(deviceId); @@ -711,9 +735,11 @@ private async Task StartReportPlansAsync( cancellationToken.ThrowIfCancellationRequested(); try { - var result = plan.IsEngineAuthoritative - ? await session.Client.StartHybridReportMonitorAsync(plan, cancellationToken).ConfigureAwait(false) - : await session.Client.StartReportMonitorAsync(plan, cancellationToken).ConfigureAwait(false); + var result = session.StaticDataSetReportOnly && session.Client.HasTrustedSclOnlineAuthority + ? await session.Client.StartTrustedSclStaticReportMonitorAsync(plan, cancellationToken).ConfigureAwait(false) + : plan.IsEngineAuthoritative + ? await session.Client.StartHybridReportMonitorAsync(plan, cancellationToken).ConfigureAwait(false) + : await session.Client.StartReportMonitorAsync(plan, cancellationToken).ConfigureAwait(false); session.HybridValidation.RecordActivation(plan, result); if (!result.IsSuccess) { @@ -943,6 +969,20 @@ private async Task> BuildReportPlansForCurrentA IReadOnlyList legacyPlans, CancellationToken cancellationToken) { + if (session.StaticDataSetReportOnly && session.Client.HasTrustedSclOnlineAuthority) + { + session.HybridValidation.Reset(null); + var trustedPlans = legacyPlans.Count > 0 + ? legacyPlans + : Iec61850ReportPlanner.BuildPlans( + session.Device, + session.Points.Values, + allowDynamicDataSetWrites: false); + Log("INFO", session.Device.Name, + $"Trusted SCL report planning retained {trustedPlans.Count} local static candidate(s). DataSet membership and RCB identity remain SCL-authoritative; online directory discovery and Hybrid availability probing are bypassed."); + return trustedPlans.Where(plan => !plan.AllowDynamicDataSetWrites).ToArray(); + } + if (session.Client.CanUseHybridReportPlanner(session.Device)) { NativeHybridReportPlanningResult hybrid; @@ -1142,45 +1182,14 @@ private async Task ReceiveReportSlicesAsync(DeviceSession session, CancellationT state.ReportValueRejectedLogged = false; var receivedUtc = update.UpdatedAt == default ? DateTime.UtcNow : update.UpdatedAt.UtcDateTime; - var hasSourceTimestamp = TryParseReportTimestampUtc(update.ReportTimestamp, out var reportSourceUtc); - var commandValueMatches = update.HasValue && state.AwaitingCommandReportEdge && - AreSemanticallyEquivalent(point, state.CommandFeedbackValue, display); - var contradictsCommandFeedback = update.HasValue && state.AwaitingCommandReportEdge && - !commandValueMatches; - var provablyOlderThanCommand = contradictsCommandFeedback && hasSourceTimestamp && - reportSourceUtc < state.LastCommandFeedbackUtc.AddMilliseconds(-5); - var unlabelledSnapshotInsideGuard = contradictsCommandFeedback && !hasSourceTimestamp && - receivedUtc <= state.CommandFeedbackGuardUntilUtc && - !IsChangeReportReason(update.Reason); - if (provablyOlderThanCommand || unlabelledSnapshotInsideGuard) - { - state.ReportTrafficSeen = true; - state.LastReportUtc = DateTime.UtcNow; - if (!state.StaleReportSuppressedLogged) - { - state.StaleReportSuppressedLogged = true; - Log("WARN", session.Device.Name, - $"{point.SignalName}: stale report value {display} was suppressed after command-confirmed {state.CommandFeedbackValue}; reportTime={(hasSourceTimestamp ? reportSourceUtc.ToString("O", CultureInfo.InvariantCulture) : "not supplied")}."); - } - continue; - } - var hadValueBeforeReport = state.HasValue; var valueChangedByReport = update.HasValue && hadValueBeforeReport && HasExactSemanticEdge(point, state.Value, display); state.ReportTrafficSeen = true; state.LastReportUtc = DateTime.UtcNow; - if (commandValueMatches && - (!hasSourceTimestamp || reportSourceUtc >= state.LastCommandFeedbackUtc.AddMilliseconds(-5))) - { - state.AwaitingCommandReportEdge = false; - state.CommandReportMissLogged = false; - state.StaleReportSuppressedLogged = false; - state.ReportChangeVerified = true; - state.ReportMissLogged = false; - Log("INFO", session.Device.Name, - $"{point.SignalName}: event-driven report confirmed command feedback {display}; reason={update.Reason}; reportTime={(hasSourceTimestamp ? reportSourceUtc.ToString("O", CultureInfo.InvariantCulture) : "not supplied")}."); - } - else if (valueChangedByReport || IsChangeReportReason(update.Reason)) + // IEC 61850 process truth comes from independent acquisition, never from + // a prior control result. A real IED report is therefore never suppressed, + // rewritten, or correlated against command-side feedback before publication. + if (valueChangedByReport || IsChangeReportReason(update.Reason)) { state.ReportChangeVerified = true; state.ReportMissLogged = false; @@ -1451,15 +1460,6 @@ private async Task PollDuePointsAsync(DeviceSession session, CancellationToken c var normalizedQuality = NormalizeQuality(quality); var normalizedTimestamp = string.IsNullOrWhiteSpace(deviceTimestamp) ? "-" : deviceTimestamp; - if (reportAssigned && state.AwaitingCommandReportEdge && - nowUtc >= state.CommandReportDeadlineUtc && !state.CommandReportMissLogged) - { - state.CommandReportMissLogged = true; - state.ReportChangeVerified = false; - Log("WARN", session.Device.Name, - $"{point.SignalName}: command feedback reached {state.CommandFeedbackValue}, but no matching dchg report arrived within 2 seconds. MMS validation remains active until event delivery is proven."); - } - var pollDetectedChange = state.HasValue && !string.Equals(state.Value, display, StringComparison.Ordinal); var sourceMode = "MMS polling"; var reason = "cyclic"; @@ -1727,10 +1727,14 @@ await DisposeClientForReconnectAsync( connectTimeout.CancelAfter(SmartReconnectPolicy.ConnectBudget); try { - await replacement.ConnectAsync( - session.Device.IpAddress, - session.Device.Port, - connectTimeout.Token).ConfigureAwait(false); + var reconnectPath = await ConnectUsingSelectedFastPathAsync( + session, + connectTimeout.Token, + allowCachedRetry: false).ConfigureAwait(false); + Log("INFO", session.Device.Name, + reconnectPath == Iec61850ConnectionPath.SclAssisted + ? "Smart reconnect reused verified SCL authority; no cached-association or discovery fallback was attempted." + : "Smart reconnect reused the saved live-model association path."); } catch (OperationCanceledException) when (!cancellationToken.IsCancellationRequested) { @@ -1893,13 +1897,6 @@ private static void ResetAssociationReportEvidence(DeviceSession session) state.ReportChangeVerified = false; state.LastReportUtc = DateTime.MinValue; state.ReportMissLogged = false; - state.AwaitingCommandReportEdge = false; - state.CommandReportMissLogged = false; - state.StaleReportSuppressedLogged = false; - state.CommandFeedbackValue = string.Empty; - state.LastCommandFeedbackUtc = DateTime.MinValue; - state.CommandFeedbackGuardUntilUtc = DateTime.MinValue; - state.CommandReportDeadlineUtc = DateTime.MinValue; state.AcquisitionLabel = session.StaticDataSetReportOnly ? "Static DataSet report rearming" : "MMS polling"; state.SourceMode = session.StaticDataSetReportOnly ? "Static DataSet report rearming" @@ -2435,71 +2432,6 @@ private static void IndexPointReference(DeviceSession session, Iec61850MonitorPo session.ReportReferenceIndex.TryAdd(key, point); } - private static IReadOnlyList BuildControlFeedbackReferences(SignalDefinition signal) - { - var references = new List(3); - void Add(string? reference) - { - if (string.IsNullOrWhiteSpace(reference)) - return; - var trimmed = reference.Trim(); - if (!references.Contains(trimmed, StringComparer.OrdinalIgnoreCase)) - references.Add(trimmed); - } - - Add(signal.ControlStatusReference); - Add(signal.ObjectReference); - if (!string.IsNullOrWhiteSpace(signal.ObjectReference) && - !NormalizeReference(signal.ObjectReference).EndsWith(".stval", StringComparison.OrdinalIgnoreCase)) - { - Add(signal.ObjectReference.TrimEnd('.') + ".stVal"); - } - return references; - } - - private static Iec61850MonitorPoint? FindPointForControlFeedback( - DeviceSession session, - IReadOnlyList references) - { - foreach (var reference in references) - { - var exact = FindPointForReportReference(session, reference); - if (exact != null) - return exact; - } - - // Some IEDs expose control objects with the IED name prepended to the MMS - // domain (for example OLSF501CB1) while the live point uses CB1. Match the - // member path plus a unique domain suffix, never the member path alone when - // more than one monitored logical device could match. - foreach (var reference in references) - { - var source = CanonicalDataReference(reference); - var sourceSlash = source.IndexOf('/'); - if (sourceSlash <= 0 || sourceSlash >= source.Length - 1) - continue; - var sourceDomain = source[..sourceSlash]; - var sourceMember = source[(sourceSlash + 1)..]; - var candidates = session.Points.Values.Where(candidate => - { - var target = CanonicalDataReference(candidate.IecReference); - var targetSlash = target.IndexOf('/'); - if (targetSlash <= 0 || targetSlash >= target.Length - 1) - return false; - var targetDomain = target[..targetSlash]; - var targetMember = target[(targetSlash + 1)..]; - return sourceMember.Equals(targetMember, StringComparison.OrdinalIgnoreCase) && - (sourceDomain.EndsWith(targetDomain, StringComparison.OrdinalIgnoreCase) || - targetDomain.EndsWith(sourceDomain, StringComparison.OrdinalIgnoreCase)); - }).Distinct().ToArray(); - - if (candidates.Length == 1) - return candidates[0]; - } - - return null; - } - private static Iec61850MonitorPoint? FindPointForReportReference(DeviceSession session, string reference) { foreach (var key in GetReferenceKeys(reference)) diff --git a/Services/NativeIec61850Client.SclAssisted.cs b/Services/NativeIec61850Client.SclAssisted.cs new file mode 100644 index 000000000..008453011 --- /dev/null +++ b/Services/NativeIec61850Client.SclAssisted.cs @@ -0,0 +1,545 @@ +using System.Diagnostics; +using AR.Iec61850.Discovery; +using ArMms = AR.Iec61850.Mms; +using ArScl = AR.Iec61850.Scl; + +namespace ArIED61850Tester.Services; + +public sealed class SclAssistedClientConnectResult +{ + public bool IsSuccess { get; init; } + public SclAssistedConnectionPreparation Preparation { get; init; } = new(); + public ArScl.SclAssistedMmsOnlineResult? Online { get; init; } + public ArMms.InitialFcReadExecutionResult? InitialRead { get; init; } + public IReadOnlyList Warnings { get; init; } = Array.Empty(); + public TimeSpan AssociationValidationDuration { get; init; } + public TimeSpan InitialReadDuration { get; init; } + public TimeSpan TotalDuration { get; init; } + public string Message { get; init; } = string.Empty; +} + +internal sealed class TrustedSclInitialValue +{ + public string Reference { get; init; } = string.Empty; + public string FunctionalConstraint { get; init; } = string.Empty; + public string SclBType { get; init; } = string.Empty; + public object? Value { get; init; } +} + +public sealed partial class NativeIec61850Client +{ + private readonly Dictionary _trustedSclDataSetDirectories = + new(StringComparer.OrdinalIgnoreCase); + private readonly Dictionary _trustedSclInitialValues = + new(StringComparer.OrdinalIgnoreCase); + private bool _trustedSclOnlineAuthorityActive; + + internal bool HasTrustedSclOnlineAuthority => _trustedSclOnlineAuthorityActive; + internal int TrustedSclInitialValueCount => _trustedSclOnlineAuthorityActive ? _trustedSclInitialValues.Count : 0; + + internal IReadOnlyList TrustedSclReportControls + => _trustedSclOnlineAuthorityActive && _lastDiscovery is not null + ? _lastDiscovery.ReportInventory.ReportControls + : Array.Empty(); + + internal bool TryGetTrustedSclDataSetDirectory( + string dataSetReference, + out ArMms.MmsDataSetDirectoryResult directory) + { + directory = null!; + if (!_trustedSclOnlineAuthorityActive) + return false; + + return _trustedSclDataSetDirectories.TryGetValue( + NormalizeTrustedSclReference(dataSetReference), + out directory!); + } + + internal bool TryGetTrustedSclInitialValue( + string reference, + out TrustedSclInitialValue value) + { + value = null!; + if (!_trustedSclOnlineAuthorityActive) + return false; + + return _trustedSclInitialValues.TryGetValue( + NormalizeTrustedSclReference(reference), + out value!); + } + + private void ResetTrustedSclOnlineAuthority() + { + _trustedSclOnlineAuthorityActive = false; + _trustedSclDataSetDirectories.Clear(); + _trustedSclInitialValues.Clear(); + } + + public Task ConnectUsingSclAsync( + string sclXml, + string iedName, + string accessPointName, + string host, + int port, + CancellationToken cancellationToken) + => ConnectUsingSclAsync( + sclXml, + iedName, + accessPointName, + host, + port, + ArMms.MmsReadBatchCodec.MaximumVariableReferencesPerRead, + cancellationToken); + + /// + /// Opens the trusted-SCL online path: exact SCL association identity, one Domain/VMD + /// reconciliation, then bounded sequential FC-root initial Reads. Static DataSet and + /// ReportControl authority is retained from the SCL model in memory; no live directory + /// discovery is introduced behind this path. + /// + public async Task ConnectUsingSclAsync( + string sclXml, + string iedName, + string accessPointName, + string host, + int port, + int maximumVariableReferencesPerRead, + CancellationToken cancellationToken) + { + var totalWatch = Stopwatch.StartNew(); + var associationDuration = TimeSpan.Zero; + var initialReadDuration = TimeSpan.Zero; + + ResetTrustedSclOnlineAuthority(); + await DisposeControlSessionsAsync().ConfigureAwait(false); + LastErrorMessage = string.Empty; + LastConnectionFailureKind = string.Empty; + LastConnectionTechnicalSummary = string.Empty; + LastDiscoverySummary = string.Empty; + _lastDiscovery = null; + _liveModel = null; + LastReportInventory = new NativeReportInventory(); + _reportMonitorSessions.Clear(); + _reportMonitorCoverage.Clear(); + ResetSemanticReportProjectionContext(); + Interlocked.Exchange(ref _engineCompatibilityWarningIssued, 0); + DetectedIdentity = new Iec61850DeviceIdentity(); + _host = host?.Trim() ?? string.Empty; + _port = port <= 0 ? 102 : port; + + var preparation = SclAssistedConnectionPreparationBuilder.Build( + sclXml, + iedName, + accessPointName, + _host, + _port, + maximumVariableReferencesPerRead); + if (!preparation.IsSuccess || + preparation.AssociationPlan is null || + preparation.InitialReadDesign is null || + preparation.InitialReadPlan is null) + { + LastConnectionFailureKind = "SCL_PLAN_INVALID"; + LastErrorMessage = preparation.Errors.Count == 0 + ? "SCL-assisted connection preparation failed." + : string.Join(" | ", preparation.Errors); + LastConnectionTechnicalSummary = LastErrorMessage; + totalWatch.Stop(); + return new SclAssistedClientConnectResult + { + Preparation = preparation, + Warnings = preparation.Warnings, + TotalDuration = totalWatch.Elapsed, + Message = LastErrorMessage + }; + } + + try + { + var associationWatch = Stopwatch.StartNew(); + var online = await _session.ConnectSclAssistedAsync( + preparation.AssociationPlan, + preparation.DomainInventory, + TimeSpan.FromSeconds(8), + cancellationToken).ConfigureAwait(false); + associationWatch.Stop(); + associationDuration = associationWatch.Elapsed; + + if (!online.IsCompatible) + { + LastConnectionFailureKind = online.Status.ToString(); + LastErrorMessage = online.Message; + LastConnectionTechnicalSummary = online.Domains?.Summary ?? online.Message; + await _session.DisposeAsync().ConfigureAwait(false); + totalWatch.Stop(); + return new SclAssistedClientConnectResult + { + Preparation = preparation, + Online = online, + Warnings = preparation.Warnings, + AssociationValidationDuration = associationDuration, + TotalDuration = totalWatch.Elapsed, + Message = LastErrorMessage + }; + } + + var readWatch = Stopwatch.StartNew(); + var initialRead = await _session.ExecuteInitialFcReadPlanAsync( + preparation.InitialReadPlan, + TimeSpan.FromSeconds(5), + cancellationToken).ConfigureAwait(false); + readWatch.Stop(); + initialReadDuration = readWatch.Elapsed; + + if (initialRead.Status is ArMms.InitialFcReadExecutionStatus.InvalidPlan + or ArMms.InitialFcReadExecutionStatus.SessionNotReady + or ArMms.InitialFcReadExecutionStatus.TimedOut + or ArMms.InitialFcReadExecutionStatus.TransportFailure) + { + LastConnectionFailureKind = $"INITIAL_FC_READ_{initialRead.Status}"; + LastErrorMessage = initialRead.Message; + LastConnectionTechnicalSummary = initialRead.Message; + await _session.DisposeAsync().ConfigureAwait(false); + totalWatch.Stop(); + return new SclAssistedClientConnectResult + { + Preparation = preparation, + Online = online, + InitialRead = initialRead, + Warnings = preparation.Warnings, + AssociationValidationDuration = associationDuration, + InitialReadDuration = initialReadDuration, + TotalDuration = totalWatch.Elapsed, + Message = LastErrorMessage + }; + } + + var reconciledDomains = online.Domains?.MatchedDomains + ?? preparation.DomainInventory.ExpectedDomains; + var domainVariables = reconciledDomains + .Distinct(StringComparer.Ordinal) + .ToDictionary( + domain => domain, + _ => (IReadOnlyList)Array.Empty(), + StringComparer.Ordinal); + + _liveModel = preparation.InitialReadDesign.Model; + var reportInventory = BuildTrustedSclReportInventory(_liveModel); + var dataSetDirectories = BuildTrustedSclDataSetDirectories(_liveModel); + foreach (var directory in dataSetDirectories) + { + _trustedSclDataSetDirectories[ + NormalizeTrustedSclReference(directory.DataSetReference)] = directory; + } + + foreach (var leaf in initialRead.Batches + .SelectMany(batch => batch.Projections) + .SelectMany(projection => projection.Leaves)) + { + if (string.IsNullOrWhiteSpace(leaf.Reference)) + continue; + + _trustedSclInitialValues[NormalizeTrustedSclReference(leaf.Reference)] = new TrustedSclInitialValue + { + Reference = leaf.Reference, + FunctionalConstraint = leaf.FunctionalConstraint, + SclBType = leaf.SclBType, + Value = ConvertTrustedSclInitialValue(leaf.Value) + }; + } + + _lastDiscovery = new ArMms.MmsDiscoveryResult + { + Snapshot = new ArMms.MmsDiscoverySnapshot + { + DomainVariables = domainVariables, + DomainVariableLists = new Dictionary>(StringComparer.Ordinal) + }, + ReportInventory = reportInventory, + IedDirectory = new ArMms.MmsIedModelDirectory(Array.Empty()), + DataSetDirectories = dataSetDirectories, + Summary = + "Trusted SCL authority: Domain/VMD validation and bounded FC-root snapshot completed; " + + "static DataSet/RCB authority retained locally; full live discovery intentionally skipped." + }; + LastReportInventory = ToNativeInventory(reportInventory); + _trustedSclOnlineAuthorityActive = true; + + var projectionErrors = initialRead.Batches + .Sum(batch => batch.Projections.Sum(projection => projection.Errors.Count)); + var extraDomains = online.Domains?.ExtraObservedDomains.Count ?? 0; + var partial = initialRead.Status == ArMms.InitialFcReadExecutionStatus.Partial; + LastDiscoverySummary = + $"SCL-assisted MMS: domains={reconciledDomains.Count}, extraOnlineDomains={extraDomains}, " + + $"FC-roots={initialRead.Plan.Targets.Count}, successfulReads={initialRead.SuccessfulTargetCount}, " + + $"failedReads={initialRead.FailedTargetCount}, projectedLeaves={initialRead.ProjectedLeafCount}, " + + $"initialValueCache={_trustedSclInitialValues.Count}, projectionErrors={projectionErrors}, maxVariablesPerRead={initialRead.Plan.MaximumVariableReferencesPerRead}, " + + $"staticDataSets={dataSetDirectories.Count}, staticRCB={reportInventory.ReportControls.Count}, fullDiscovery=skipped."; + LastConnectionFailureKind = string.Empty; + LastConnectionTechnicalSummary = online.Domains?.Summary ?? online.Message; + LastErrorMessage = partial + ? "SCL-assisted association is healthy, but one or more initial FC-root values could not be read or projected. The trusted SCL model was preserved." + : string.Empty; + + var warnings = preparation.Warnings + .Concat(extraDomains > 0 + ? new[] { $"IED exposes {extraDomains} extra online MMS domain(s); they remain evidence only and do not mutate the SCL model." } + : Array.Empty()) + .Concat(partial ? new[] { LastErrorMessage } : Array.Empty()) + .Where(message => !string.IsNullOrWhiteSpace(message)) + .Distinct(StringComparer.Ordinal) + .ToArray(); + + totalWatch.Stop(); + return new SclAssistedClientConnectResult + { + IsSuccess = true, + Preparation = preparation, + Online = online, + InitialRead = initialRead, + Warnings = warnings, + AssociationValidationDuration = associationDuration, + InitialReadDuration = initialReadDuration, + TotalDuration = totalWatch.Elapsed, + Message = LastDiscoverySummary + }; + } + catch (OperationCanceledException) + { + ResetTrustedSclOnlineAuthority(); + totalWatch.Stop(); + await _session.DisposeAsync().ConfigureAwait(false); + throw; + } + catch (Exception ex) when (ex is IOException or InvalidDataException or InvalidOperationException or ObjectDisposedException) + { + ResetTrustedSclOnlineAuthority(); + totalWatch.Stop(); + LastConnectionFailureKind = "SCL_ASSISTED_RUNTIME_FAILURE"; + LastErrorMessage = $"SCL-assisted MMS connection failed: {ex.GetType().Name}: {ex.Message}"; + LastConnectionTechnicalSummary = LastErrorMessage; + await _session.DisposeAsync().ConfigureAwait(false); + return new SclAssistedClientConnectResult + { + Preparation = preparation, + Warnings = preparation.Warnings, + AssociationValidationDuration = associationDuration, + InitialReadDuration = initialReadDuration, + TotalDuration = totalWatch.Elapsed, + Message = LastErrorMessage + }; + } + } + + private static ArMms.MmsReportInventory BuildTrustedSclReportInventory( + LiveIedModelDiscoveryDocument model) + { + var inventory = new ArMms.MmsReportInventory(); + foreach (var dataSet in model.DataSets) + { + var (domain, itemName) = ParseTrustedSclDataSetReference( + dataSet.Reference, + dataSet.Domain, + dataSet.LogicalNode, + dataSet.Name); + inventory.DataSets.Add(new ArMms.MmsDataSetCandidate + { + Domain = domain, + LogicalNode = dataSet.LogicalNode, + Name = dataSet.Name, + Reference = dataSet.Reference, + RawMmsName = itemName + }); + } + + foreach (var report in model.ReportControls) + { + var reference = ConcreteFirstStaticRcbReference(report.Reference, report.Indexed); + var candidate = new ArMms.MmsReportControlCandidate + { + Domain = report.Domain, + LogicalNode = report.LogicalNode, + FunctionalConstraint = report.Buffered ? "BR" : "RP", + Name = StaticRcbLeaf(reference), + Reference = reference, + Buffered = report.Buffered, + DataSetReference = report.DataSetReference, + DataSetProbeState = ArMms.MmsRcbDataSetProbeState.NotAttempted, + DataSetProbeMessage = "Trusted SCL authority; no live DataSet probe performed.", + ReportId = report.ReportId, + ConfRev = report.ConfRev, + IntegrityPeriodMs = report.IntegrityPeriodMs, + EnabledState = report.EnabledState, + ReservationState = report.ReservationState, + ReservationTimeSeconds = report.ReservationTimeSeconds, + BufferTimeMs = report.BufferTimeMs, + TriggerOptions = report.TriggerOptions, + OptionalFields = report.OptionalFields, + Status = "TrustedSclAuthority" + }; + + candidate.Attributes.AddRange(report.Buffered + ? new[] + { + "RptID", "RptEna", "DatSet", "ConfRev", "OptFlds", "BufTm", "SqNum", + "TrgOps", "IntgPd", "GI", "PurgeBuf", "EntryID", "TimeOfEntry", "ResvTms", "Owner" + } + : new[] + { + "RptID", "RptEna", "Resv", "DatSet", "ConfRev", "OptFlds", "BufTm", + "SqNum", "TrgOps", "IntgPd", "GI", "Owner" + }); + inventory.ReportControls.Add(candidate); + } + + return inventory; + } + + private static IReadOnlyList BuildTrustedSclDataSetDirectories( + LiveIedModelDiscoveryDocument model) + => model.DataSets + .Select(dataSet => + { + var (domain, itemName) = ParseTrustedSclDataSetReference( + dataSet.Reference, + dataSet.Domain, + dataSet.LogicalNode, + dataSet.Name); + var members = dataSet.Members + .OrderBy(member => member.Index) + .Select(member => BuildTrustedSclDataSetMember(member, domain)) + .ToArray(); + return new ArMms.MmsDataSetDirectoryResult + { + IsSuccess = members.Length > 0, + DataSetReference = dataSet.Reference, + Domain = domain, + DataSetMmsName = itemName, + IsDeletable = dataSet.IsDeletable, + Members = members, + Message = + $"Trusted SCL DataSet authority: {dataSet.Reference} has {members.Length} ordered member(s); no network directory request was sent." + }; + }) + .ToArray(); + + private static ArMms.MmsDataSetDirectoryMember BuildTrustedSclDataSetMember( + LiveIedDataSetMemberModel member, + string fallbackDomain) + { + var mmsReference = member.MmsReference?.Trim() ?? string.Empty; + var slash = mmsReference.IndexOf('/'); + var domain = slash > 0 ? mmsReference[..slash] : fallbackDomain; + var itemName = slash > 0 && slash + 1 < mmsReference.Length + ? mmsReference[(slash + 1)..] + : BuildMmsItemNameFromUserReference(member.Reference, member.FunctionalConstraint); + var tokens = itemName.Split('$', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + var logicalNode = tokens.FirstOrDefault() ?? string.Empty; + var dataObjectPath = tokens.Length > 2 + ? string.Join('.', tokens.Skip(2)) + : string.Empty; + + return new ArMms.MmsDataSetDirectoryMember + { + Domain = domain, + MmsItemName = itemName, + UserReference = member.Reference, + FunctionalConstraint = member.FunctionalConstraint, + LogicalNode = logicalNode, + DataObjectPath = dataObjectPath, + Source = "TrustedScl", + Confidence = 100 + }; + } + + private static (string Domain, string ItemName) ParseTrustedSclDataSetReference( + string reference, + string fallbackDomain, + string logicalNode, + string name) + { + var normalized = reference?.Trim() ?? string.Empty; + var slash = normalized.IndexOf('/'); + var domain = slash > 0 ? normalized[..slash] : fallbackDomain; + var tail = slash > 0 && slash + 1 < normalized.Length + ? normalized[(slash + 1)..] + : string.Empty; + var itemName = string.IsNullOrWhiteSpace(tail) + ? $"{(string.IsNullOrWhiteSpace(logicalNode) ? "LLN0" : logicalNode)}${name}" + : tail.Replace('.', '$'); + if (!itemName.Contains('$', StringComparison.Ordinal)) + itemName = $"LLN0${itemName}"; + return (domain, itemName); + } + + private static string BuildMmsItemNameFromUserReference(string reference, string functionalConstraint) + { + var normalized = reference?.Trim() ?? string.Empty; + var slash = normalized.IndexOf('/'); + var tail = slash >= 0 && slash + 1 < normalized.Length + ? normalized[(slash + 1)..] + : normalized; + var parts = tail.Split('.', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries); + if (parts.Length == 0) + return string.Empty; + var logicalNode = parts[0]; + var dataPath = parts.Length > 1 ? string.Join('$', parts.Skip(1)) : string.Empty; + return string.IsNullOrWhiteSpace(dataPath) + ? $"{logicalNode}${functionalConstraint}" + : $"{logicalNode}${functionalConstraint}${dataPath}"; + } + + private static string ConcreteFirstStaticRcbReference(string reference, bool indexed) + { + var normalized = reference?.Trim() ?? string.Empty; + if (string.IsNullOrWhiteSpace(normalized) || !indexed) + return normalized; + + var separator = Math.Max(normalized.LastIndexOf('$'), normalized.LastIndexOf('.')); + var leaf = separator >= 0 ? normalized[(separator + 1)..] : normalized; + return leaf.Length > 0 && !char.IsDigit(leaf[^1]) + ? normalized + "01" + : normalized; + } + + private static object? ConvertTrustedSclInitialValue(ArMms.MmsDataValue value) + { + ArgumentNullException.ThrowIfNull(value); + return value.Kind switch + { + ArMms.MmsDataKind.Boolean or + ArMms.MmsDataKind.Integer or + ArMms.MmsDataKind.Unsigned or + ArMms.MmsDataKind.FloatingPoint or + ArMms.MmsDataKind.VisibleString or + ArMms.MmsDataKind.MmsString or + ArMms.MmsDataKind.UtcTime => value.Value, + ArMms.MmsDataKind.BitString => FormatTrustedSclBitString(value.RawValue), + ArMms.MmsDataKind.OctetString or ArMms.MmsDataKind.BinaryTime => + Convert.ToHexString(value.RawValue.ToArray()), + _ => value.Value + }; + } + + private static string FormatTrustedSclBitString(IReadOnlyList raw) + { + if (raw.Count == 0) + return "bits(00,unused=0)"; + + var unusedBits = raw[0]; + var data = raw.Skip(1).ToArray(); + var hex = data.Length == 0 ? "00" : Convert.ToHexString(data); + return $"bits({hex},unused={unusedBits})"; + } + + private static string StaticRcbLeaf(string reference) + { + var separator = Math.Max(reference.LastIndexOf('$'), reference.LastIndexOf('.')); + return separator >= 0 && separator + 1 < reference.Length + ? reference[(separator + 1)..] + : reference; + } + + private static string NormalizeTrustedSclReference(string? reference) + => (reference ?? string.Empty).Trim().Replace('$', '.'); +} diff --git a/Services/NativeIec61850Client.TrustedSclStaticReporting.cs b/Services/NativeIec61850Client.TrustedSclStaticReporting.cs new file mode 100644 index 000000000..63224d411 --- /dev/null +++ b/Services/NativeIec61850Client.TrustedSclStaticReporting.cs @@ -0,0 +1,217 @@ +using ArIED61850Tester.Models; +using ArMms = AR.Iec61850.Mms; + +namespace ArIED61850Tester.Services; + +/// +/// Golden-wire static-report adapter used only after a successful trusted-SCL online +/// connection. DataSet membership and configured RCB identity come from the exact SCL +/// source that established the association. No live DataSet-directory browse or dynamic +/// DataSet mutation is permitted on this path. Normal Play requests one explicit one-shot +/// GI after the receiver is installed and the trusted static RCB is armed so the initial +/// DataSet image is delivered without cyclic MMS polling. +/// +public sealed partial class NativeIec61850Client +{ + public async Task StartTrustedSclStaticReportMonitorAsync( + ReportControlPlan plan, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(plan); + cancellationToken.ThrowIfCancellationRequested(); + + if (!HasTrustedSclOnlineAuthority) + { + return TrustedSclStaticFailure( + plan, + "Trusted SCL online authority is not active for this MMS association.", + "TrustedSclAuthorityUnavailable"); + } + + if (!_session.IsMmsInitiated) + { + return TrustedSclStaticFailure( + plan, + $"Trusted SCL static report monitor requires an initiated MMS association. Current state: {_session.State}.", + "TransportUnavailable"); + } + + if (_reportMonitorSessions.ContainsKey(plan.PlanId)) + { + return new NativeReportMonitorStartResult + { + IsSuccess = true, + PlanId = plan.PlanId, + Message = $"Trusted SCL static report monitor already active for {plan.DisplayReference}.", + ReportControlReference = plan.ReportControlReference, + DataSetReference = plan.DataSetReference, + AcquisitionLabel = $"Trusted SCL: {(plan.Buffered ? "StaticBrcb" : "StaticUrcb")}", + CoveredReferences = _reportMonitorCoverage.TryGetValue(plan.PlanId, out var existingCoverage) + ? existingCoverage + : Array.Empty() + }; + } + + if (string.IsNullOrWhiteSpace(plan.DataSetReference) || + !TryGetTrustedSclDataSetDirectory(plan.DataSetReference, out var directory) || + !directory.IsSuccess || + directory.Members.Count == 0) + { + return TrustedSclStaticFailure( + plan, + $"Trusted SCL DataSet '{plan.DataSetReference}' is missing or has no ordered members. " + + "The client refused network DataSet-directory discovery and did not arm an RCB.", + "TrustedSclDataSetUnavailable"); + } + + var configuredReference = (plan.ReportControlReference ?? string.Empty).Trim(); + var candidates = TrustedSclReportControls + .Where(candidate => + string.IsNullOrWhiteSpace(candidate.DataSetReference) || + SameStaticReference(candidate.DataSetReference, directory.DataSetReference)) + .Select(candidate => new + { + Candidate = candidate, + Rank = string.IsNullOrWhiteSpace(configuredReference) + ? 0 + : Iec61850StaticRcbReferenceMatcher.MatchRank(configuredReference, candidate.Reference) + }) + .Where(item => item.Rank != int.MaxValue) + .OrderBy(item => item.Rank) + .ThenByDescending(item => item.Candidate.Buffered) + .ThenBy(item => item.Candidate.Reference, StringComparer.OrdinalIgnoreCase) + .ToArray(); + + if (candidates.Length == 0) + { + return TrustedSclStaticFailure( + plan, + $"No trusted SCL RCB matches configured reference '{plan.ReportControlReference}' and DataSet '{directory.DataSetReference}'. " + + "No peer RCB substitution or live RCB directory discovery was attempted.", + "TrustedSclRcbUnavailable"); + } + + var bestRank = candidates[0].Rank; + var best = candidates.Where(item => item.Rank == bestRank).ToArray(); + if (best.Length != 1) + { + return TrustedSclStaticFailure( + plan, + $"Trusted SCL RCB selection is ambiguous for '{plan.ReportControlReference}': {best.Length} equally ranked candidate(s). " + + "The client failed closed without enabling any RCB.", + "TrustedSclRcbAmbiguous"); + } + + var rcb = CloneReportControlForPlanning(best[0].Candidate); + if (string.IsNullOrWhiteSpace(rcb.DataSetReference)) + rcb.DataSetReference = directory.DataSetReference; + if (!SameStaticReference(rcb.DataSetReference, directory.DataSetReference)) + { + return TrustedSclStaticFailure( + plan, + $"Trusted SCL RCB {rcb.Reference} binds DataSet '{rcb.DataSetReference}', not '{directory.DataSetReference}'. " + + "RCB activation was withheld.", + "TrustedSclRcbDataSetMismatch"); + } + + var subscription = new ArMms.MmsReportSubscriptionPlan + { + Mode = ArMms.MmsReportSubscriptionPlanMode.StaticDataSet, + Status = ArMms.MmsReportSubscriptionPlanStatus.ReadyRequiresWrite, + ReportControl = rcb, + DataSetReference = directory.DataSetReference, + Members = directory.Members, + DynamicPoints = Array.Empty(), + Steps = new[] + { + $"Use trusted SCL RCB {rcb.Reference} and DataSet {directory.DataSetReference}.", + $"Use {directory.Members.Count} ordered DataSet member(s) from the verified SCL source.", + "Install InformationReport receiver before RCB activation.", + "Primary wire sequence: whole-RCB Read, optional URCB Resv, RptEna=true, two whole-RCB readbacks.", + "BRCB ResvTms is retry-only after a real direct-RptEna rejection; request one explicit GI=true after activation for the initial image." + }, + Warnings = Array.Empty() + }; + + var coveredReferences = ExtractSubscriptionMemberReferences(subscription.Members); + var start = await RunMmsOperationAsync( + () => _session.StartStaticSclReportMonitorAsync( + subscription, + triggerGeneralInterrogation: true, + cancellationToken), + cancellationToken).ConfigureAwait(false); + + var warnings = start.Warnings + .Concat(subscription.Warnings) + .Distinct(StringComparer.OrdinalIgnoreCase) + .ToArray(); + + if (!start.IsSuccess || start.Session is null) + { + return new NativeReportMonitorStartResult + { + IsSuccess = false, + PlanId = plan.PlanId, + Message = $"Trusted SCL static report activation failed for {plan.DisplayReference}: {start.Message}", + SubscriptionSummary = subscription.Summary, + MemberCount = subscription.Members.Count, + WriteStepCount = start.WriteSteps.Count, + UsedDynamicDataSet = false, + DynamicAttempted = false, + DynamicAttemptState = "NotApplicable", + FailureReason = "TrustedSclStaticActivationFailed", + ReportControlReference = plan.ReportControlReference, + DataSetReference = plan.DataSetReference, + CoveredReferences = coveredReferences, + Warnings = warnings + }; + } + + if (!string.IsNullOrWhiteSpace(start.Session.ReportControl.Reference)) + plan.ReportControlReference = start.Session.ReportControl.Reference; + if (!string.IsNullOrWhiteSpace(start.Session.Plan.DataSetReference)) + plan.DataSetReference = start.Session.Plan.DataSetReference; + plan.Buffered = start.Session.ReportControl.Buffered; + plan.IsEngineAuthoritative = true; + plan.EngineAcquisitionKind = plan.Buffered ? "StaticBrcb" : "StaticUrcb"; + + _reportMonitorSessions[plan.PlanId] = start.Session; + _reportMonitorCoverage[plan.PlanId] = coveredReferences; + + return new NativeReportMonitorStartResult + { + IsSuccess = true, + PlanId = plan.PlanId, + Message = $"Trusted SCL {plan.EngineAcquisitionKind} monitor active with one-shot GI startup request. {start.Message}", + SubscriptionSummary = subscription.Summary, + MemberCount = subscription.Members.Count, + WriteStepCount = start.WriteSteps.Count, + UsedDynamicDataSet = false, + DynamicAttempted = false, + DynamicAttemptState = "NotApplicable", + ReportControlReference = plan.ReportControlReference, + DataSetReference = plan.DataSetReference, + AcquisitionLabel = $"Trusted SCL: {plan.EngineAcquisitionKind}", + CoveredReferences = coveredReferences, + Warnings = warnings + }; + } + + private static NativeReportMonitorStartResult TrustedSclStaticFailure( + ReportControlPlan plan, + string message, + string failureReason) + => new() + { + IsSuccess = false, + PlanId = plan.PlanId, + Message = message, + UsedDynamicDataSet = false, + DynamicAttempted = false, + DynamicAttemptState = "NotApplicable", + FailureReason = failureReason, + ReportControlReference = plan.ReportControlReference, + DataSetReference = plan.DataSetReference, + CoveredReferences = Array.Empty() + }; +} diff --git a/Services/PresentationEasingMath.cs b/Services/PresentationEasingMath.cs new file mode 100644 index 000000000..3930e6856 --- /dev/null +++ b/Services/PresentationEasingMath.cs @@ -0,0 +1,56 @@ +namespace ArIED61850Tester.Services; + +/// +/// Allocation-free presentation easing helpers. These functions are intentionally presentation-only: +/// raw COMTRADE/IEC 61850 engineering values remain untouched and authoritative. +/// +public static class PresentationEasingMath +{ + public static double ExponentialAlpha(double elapsedMilliseconds, double timeConstantMilliseconds) + { + if (!double.IsFinite(timeConstantMilliseconds) || timeConstantMilliseconds <= 0.0) + return 1.0; + if (double.IsPositiveInfinity(elapsedMilliseconds)) + return 1.0; + if (!double.IsFinite(elapsedMilliseconds) || elapsedMilliseconds <= 0.0) + return 0.0; + + var alpha = 1.0 - Math.Exp(-elapsedMilliseconds / timeConstantMilliseconds); + return Math.Clamp(alpha, 0.0, 1.0); + } + + public static double Smooth(double current, double target, double elapsedMilliseconds, double timeConstantMilliseconds) + { + if (!double.IsFinite(target)) return current; + if (!double.IsFinite(current)) return target; + var alpha = ExponentialAlpha(elapsedMilliseconds, timeConstantMilliseconds); + return current + ((target - current) * alpha); + } + + public static double ShortestAngleDeltaDegrees(double currentDegrees, double targetDegrees) + { + if (!double.IsFinite(currentDegrees) || !double.IsFinite(targetDegrees)) + return 0.0; + var delta = (targetDegrees - currentDegrees) % 360.0; + if (delta >= 180.0) delta -= 360.0; + if (delta < -180.0) delta += 360.0; + return delta; + } + + public static double NormalizeAngleDegrees(double degrees) + { + if (!double.IsFinite(degrees)) return 0.0; + var normalized = degrees % 360.0; + if (normalized >= 180.0) normalized -= 360.0; + if (normalized < -180.0) normalized += 360.0; + return normalized; + } + + public static double SmoothAngleDegrees(double currentDegrees, double targetDegrees, double elapsedMilliseconds, double timeConstantMilliseconds) + { + if (!double.IsFinite(targetDegrees)) return NormalizeAngleDegrees(currentDegrees); + if (!double.IsFinite(currentDegrees)) return NormalizeAngleDegrees(targetDegrees); + var alpha = ExponentialAlpha(elapsedMilliseconds, timeConstantMilliseconds); + return NormalizeAngleDegrees(currentDegrees + (ShortestAngleDeltaDegrees(currentDegrees, targetDegrees) * alpha)); + } +} diff --git a/Services/SclAssistedConnectionPreparation.cs b/Services/SclAssistedConnectionPreparation.cs new file mode 100644 index 000000000..e37b849e9 --- /dev/null +++ b/Services/SclAssistedConnectionPreparation.cs @@ -0,0 +1,189 @@ +using System.Xml; +using ArMms = AR.Iec61850.Mms; +using ArScl = AR.Iec61850.Scl; + +namespace ArIED61850Tester.Services; + +public sealed class SclAssistedConnectionPreparation +{ + public ArScl.SclAssistedMmsAssociationPlan? AssociationPlan { get; init; } + public ArScl.SclMmsDomainInventory DomainInventory { get; init; } = new(); + public ArScl.SclInitialFcReadDesign? InitialReadDesign { get; init; } + public ArMms.InitialFcReadPlan? InitialReadPlan { get; init; } + public IReadOnlyList Errors { get; init; } = Array.Empty(); + public IReadOnlyList Warnings { get; init; } = Array.Empty(); + public bool IsSuccess => + Errors.Count == 0 && + AssociationPlan is not null && + DomainInventory.IsSuccess && + InitialReadDesign?.IsSuccess == true && + InitialReadPlan?.IsValid == true; +} + +/// +/// Pure Step-5 orchestration preparation. It converts one trusted SCL IED/AccessPoint +/// plus the operator-bound TCP endpoint into the exact ARIEC61850 association/domain/ +/// initial-read contracts. It performs no socket I/O and never falls back to discovery. +/// +public static class SclAssistedConnectionPreparationBuilder +{ + public static SclAssistedConnectionPreparation Build( + string sclXml, + string iedName, + string accessPointName, + string host, + int port, + int maximumVariableReferencesPerRead = ArMms.MmsReadBatchCodec.MaximumVariableReferencesPerRead) + { + var errors = new List(); + var warnings = new List(); + var normalizedHost = (host ?? string.Empty).Trim(); + var normalizedIed = (iedName ?? string.Empty).Trim(); + var normalizedAccessPoint = (accessPointName ?? string.Empty).Trim(); + var normalizedPort = port <= 0 ? 102 : port; + + if (string.IsNullOrWhiteSpace(sclXml)) + errors.Add("SCL XML is empty."); + if (string.IsNullOrWhiteSpace(normalizedIed)) + errors.Add("An exact SCL IED name is required."); + if (string.IsNullOrWhiteSpace(normalizedAccessPoint)) + errors.Add("An exact SCL AccessPoint name is required."); + if (string.IsNullOrWhiteSpace(normalizedHost)) + errors.Add("A TCP endpoint is required before SCL-assisted connect."); + if (normalizedPort is < 1 or > 65535) + errors.Add($"TCP port must be in 1..65535; received {normalizedPort}."); + if (maximumVariableReferencesPerRead is < 1 or > ArMms.MmsReadBatchCodec.MaximumVariableReferencesPerRead) + { + errors.Add( + $"Initial Read batch size must be in 1..{ArMms.MmsReadBatchCodec.MaximumVariableReferencesPerRead}; received {maximumVariableReferencesPerRead}."); + } + + if (errors.Count > 0) + return Fail(errors, warnings); + + ArScl.SclMmsAssociationProfileSet profileSet; + try + { + profileSet = ArScl.SclMmsAssociationProfileReader.Read(sclXml); + } + catch (XmlException ex) + { + errors.Add($"SCL XML is malformed: {ex.Message}"); + return Fail(errors, warnings); + } + catch (Exception ex) when (ex is InvalidDataException or ArgumentException or InvalidOperationException) + { + errors.Add($"SCL MMS communication profile could not be read: {ex.GetType().Name}: {ex.Message}"); + return Fail(errors, warnings); + } + + warnings.AddRange(profileSet.Warnings); + var matches = profileSet.AccessPoints + .Where(profile => + string.Equals(profile.IedName, normalizedIed, StringComparison.Ordinal) && + string.Equals(profile.AccessPointName, normalizedAccessPoint, StringComparison.Ordinal)) + .ToArray(); + + if (matches.Length != 1) + { + errors.Add(matches.Length == 0 + ? $"SCL Communication has no exact ConnectedAP for IED '{normalizedIed}' / AccessPoint '{normalizedAccessPoint}'." + : $"SCL Communication has {matches.Length} exact ConnectedAP entries for IED '{normalizedIed}' / AccessPoint '{normalizedAccessPoint}'; association identity is ambiguous."); + return Fail(errors, warnings); + } + + var sclRemote = matches[0]; + var sclHost = (sclRemote.Endpoint.IpAddress ?? string.Empty).Trim(); + if (string.IsNullOrWhiteSpace(sclHost)) + { + warnings.Add($"SCL ConnectedAP has no IP address; using the explicit endpoint binding '{normalizedHost}'."); + } + else if (!string.Equals(sclHost, normalizedHost, StringComparison.OrdinalIgnoreCase)) + { + warnings.Add($"SCL IP '{sclHost}' differs from the explicit endpoint binding '{normalizedHost}'; TCP uses the explicit binding while OSI association identity remains SCL-derived."); + } + + // TCP endpoint binding is an application-level choice. Preserve every called-side + // OSI identity value from SCL and change only the network endpoint presented to + // the pure ARIEC association planner. + var effectiveRemote = new ArScl.SclMmsAccessPoint + { + IedName = sclRemote.IedName, + AccessPointName = sclRemote.AccessPointName, + SubNetworkName = sclRemote.SubNetworkName, + SubNetworkType = sclRemote.SubNetworkType, + Endpoint = new ArScl.SclMmsEndpoint + { + IpAddress = normalizedHost, + IpSubnet = sclRemote.Endpoint.IpSubnet, + IpGateway = sclRemote.Endpoint.IpGateway + }, + Association = sclRemote.Association, + Parameters = sclRemote.Parameters + }; + + var association = ArScl.SclAssistedMmsAssociationPlanBuilder.BuildExact( + effectiveRemote, + ArScl.MmsLocalAssociationProfile.SclInteroperabilityDefault); + warnings.AddRange(association.Warnings); + if (!association.IsSuccess || association.Plan is null) + { + errors.AddRange(association.Errors); + return Fail(errors, warnings); + } + + var runtimePlan = new ArScl.SclAssistedMmsAssociationPlan + { + Host = normalizedHost, + Port = normalizedPort, + IedName = association.Plan.IedName, + AccessPointName = association.Plan.AccessPointName, + LocalProfileName = association.Plan.LocalProfileName, + Cotp = association.Plan.Cotp, + Association = association.Plan.Association, + CotpConnectRequest = association.Plan.CotpConnectRequest, + SessionPresentationAcseMmsRequest = association.Plan.SessionPresentationAcseMmsRequest + }; + + var domains = ArScl.SclMmsDomainInventoryReader.Read(sclXml, normalizedIed, normalizedAccessPoint); + warnings.AddRange(domains.Warnings); + if (!domains.IsSuccess) + errors.AddRange(domains.Errors); + + var design = ArScl.SclInitialFcReadDesignBuilder.Read(sclXml, normalizedIed, normalizedAccessPoint); + warnings.AddRange(design.Warnings); + if (!design.IsSuccess) + errors.AddRange(design.Errors); + + ArMms.InitialFcReadPlan? initialReadPlan = null; + if (design.IsSuccess && domains.IsSuccess) + { + initialReadPlan = ArMms.InitialFcReadPlanner.FromSclModel( + design.Model, + domains.ExpectedDomains, + maximumVariableReferencesPerRead); + warnings.AddRange(initialReadPlan.Warnings); + if (!initialReadPlan.IsValid) + errors.AddRange(initialReadPlan.Errors); + } + + return new SclAssistedConnectionPreparation + { + AssociationPlan = runtimePlan, + DomainInventory = domains, + InitialReadDesign = design, + InitialReadPlan = initialReadPlan, + Errors = errors.Distinct(StringComparer.Ordinal).ToArray(), + Warnings = warnings.Distinct(StringComparer.Ordinal).ToArray() + }; + } + + private static SclAssistedConnectionPreparation Fail( + IReadOnlyCollection errors, + IReadOnlyCollection warnings) + => new() + { + Errors = errors.Where(message => !string.IsNullOrWhiteSpace(message)).Distinct(StringComparer.Ordinal).ToArray(), + Warnings = warnings.Where(message => !string.IsNullOrWhiteSpace(message)).Distinct(StringComparer.Ordinal).ToArray() + }; +} diff --git a/Services/SclSafeTrialGlobalUsings.cs b/Services/SclSafeTrialGlobalUsings.cs new file mode 100644 index 000000000..e662eefc9 --- /dev/null +++ b/Services/SclSafeTrialGlobalUsings.cs @@ -0,0 +1 @@ +global using ArIED61850Tester.Models; diff --git a/Services/SclSafeTrialRunner.cs b/Services/SclSafeTrialRunner.cs new file mode 100644 index 000000000..4b8490600 --- /dev/null +++ b/Services/SclSafeTrialRunner.cs @@ -0,0 +1,288 @@ +using System.Diagnostics; +using System.Security.Cryptography; +using System.Text.Json; +using System.Xml.Linq; +using ArMms = AR.Iec61850.Mms; + +namespace ArIED61850Tester.Services; + +public sealed record SclSafeTrialCommand( + string SclPath, + string IedName, + string AccessPointName, + string Host, + int Port, + int MaximumVariableReferencesPerRead, + string EvidencePath) +{ + public const string Switch = "--scl-safe-trial"; + public const string SingleReferenceSwitch = "--scl-safe-trial-single"; + + public static bool IsRequested(IReadOnlyList args) + => args.Any(argument => + string.Equals(argument, Switch, StringComparison.OrdinalIgnoreCase) || + string.Equals(argument, SingleReferenceSwitch, StringComparison.OrdinalIgnoreCase)); + + public static bool TryParse(IReadOnlyList args, out SclSafeTrialCommand? command, out string error) + { + command = null; + error = string.Empty; + if (args.Count == 0 || + (!string.Equals(args[0], Switch, StringComparison.OrdinalIgnoreCase) && + !string.Equals(args[0], SingleReferenceSwitch, StringComparison.OrdinalIgnoreCase))) + { + error = $"Expected {Switch} or {SingleReferenceSwitch} as the first argument."; + return false; + } + + if (args.Count < 5) + { + error = + $"Usage: ARSAS.exe {Switch} [port] [evidence JSON path]. " + + $"Use {SingleReferenceSwitch} with the same arguments for a controlled one-variable-per-Read interoperability trial."; + return false; + } + + var sclPath = Path.GetFullPath(args[1]); + var iedName = (args[2] ?? string.Empty).Trim(); + var accessPointName = (args[3] ?? string.Empty).Trim(); + var host = (args[4] ?? string.Empty).Trim(); + var port = 102; + if (args.Count >= 6 && (!int.TryParse(args[5], out port) || port is < 1 or > 65535)) + { + error = $"Invalid MMS TCP port '{args[5]}'; expected 1..65535."; + return false; + } + + if (string.IsNullOrWhiteSpace(iedName) || string.IsNullOrWhiteSpace(accessPointName) || string.IsNullOrWhiteSpace(host)) + { + error = "IED name, AccessPoint name and host/IP are required."; + return false; + } + + var maximumVariableReferencesPerRead = string.Equals( + args[0], + SingleReferenceSwitch, + StringComparison.OrdinalIgnoreCase) + ? 1 + : ArMms.MmsReadBatchCodec.MaximumVariableReferencesPerRead; + + var evidencePath = args.Count >= 7 && !string.IsNullOrWhiteSpace(args[6]) + ? Path.GetFullPath(args[6]) + : Path.Combine( + Path.GetTempPath(), + $"ARSAS-SCL-Trial-{DateTime.UtcNow:yyyyMMdd-HHmmss}-{maximumVariableReferencesPerRead}ref-{Guid.NewGuid():N}.json"); + + command = new SclSafeTrialCommand( + sclPath, + iedName, + accessPointName, + host, + port, + maximumVariableReferencesPerRead, + evidencePath); + return true; + } +} + +public sealed record SclSafeTrialRunResult( + int ExitCode, + bool IsSuccess, + string Message, + string EvidencePath); + +/// +/// Read-only laboratory entry point for physically validating the SCL-assisted MMS path. +/// It performs association, Domain/VMD reconciliation and bounded initial FC-root Reads only. +/// The process exits immediately afterwards, so reporting, control, writes and hidden full +/// discovery cannot be entered by this trial path. +/// +public static class SclSafeTrialRunner +{ + public static async Task RunAsync( + IReadOnlyList args, + CancellationToken cancellationToken = default) + { + if (!SclSafeTrialCommand.TryParse(args, out var command, out var parseError) || command is null) + return await WriteInputFailureAsync(args, parseError, cancellationToken).ConfigureAwait(false); + + var stopwatch = Stopwatch.StartNew(); + string sourceSha256 = string.Empty; + SclAssistedClientConnectResult? result = null; + Iec61850DeviceDiagnosticSnapshot? diagnostic = null; + string message; + var exitCode = 0; + + try + { + if (!File.Exists(command.SclPath)) + throw new FileNotFoundException("SCL/CID source file was not found.", command.SclPath); + + var sourceBytes = await File.ReadAllBytesAsync(command.SclPath, cancellationToken).ConfigureAwait(false); + sourceSha256 = Convert.ToHexString(SHA256.HashData(sourceBytes)).ToLowerInvariant(); + + // Let an XML parser honor the document encoding and normalize only the in-memory + // representation passed to the pure SCL planners. The evidence hash remains over + // the exact source bytes selected by the operator. + var document = XDocument.Load(command.SclPath, LoadOptions.PreserveWhitespace | LoadOptions.SetLineInfo); + var sclXml = document.ToString(SaveOptions.DisableFormatting); + + var client = new NativeIec61850Client(); + result = await client.ConnectUsingSclAsync( + sclXml, + command.IedName, + command.AccessPointName, + command.Host, + command.Port, + command.MaximumVariableReferencesPerRead, + cancellationToken).ConfigureAwait(false); + + diagnostic = client.CaptureDiagnosticSnapshot("SCL safe trial"); + message = result.Message; + exitCode = result.IsSuccess ? 0 : 31; + } + catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested) + { + message = "SCL safe trial was cancelled by the operator."; + exitCode = 32; + } + catch (Exception ex) + { + message = $"SCL safe trial failed before completion: {ex.GetType().Name}: {ex.Message}"; + exitCode = 33; + } + finally + { + stopwatch.Stop(); + } + + var evidence = new + { + schema = "arsas-scl-safe-trial-v2", + capturedAtUtc = DateTimeOffset.UtcNow, + safety = new + { + readOnly = true, + fullDiscoveryAllowed = false, + writesAllowed = false, + controlAllowed = false, + reportEnableAllowed = false, + dynamicDataSetAllowed = false, + automaticReadFallbackAllowed = false + }, + source = new + { + path = command.SclPath, + sha256 = sourceSha256, + iedName = command.IedName, + accessPointName = command.AccessPointName, + host = command.Host, + port = command.Port + }, + trialMode = new + { + maximumVariableReferencesPerRead = command.MaximumVariableReferencesPerRead, + label = command.MaximumVariableReferencesPerRead == 1 + ? "single-reference-control" + : "bounded-multi-reference" + }, + timing = new + { + processTotalMilliseconds = stopwatch.Elapsed.TotalMilliseconds, + connectionTotalMilliseconds = result?.TotalDuration.TotalMilliseconds ?? 0d, + associationAndDomainValidationMilliseconds = result?.AssociationValidationDuration.TotalMilliseconds ?? 0d, + initialReadMilliseconds = result?.InitialReadDuration.TotalMilliseconds ?? 0d + }, + result = new + { + success = result?.IsSuccess == true, + exitCode, + message, + warnings = result?.Warnings ?? Array.Empty(), + preparationErrors = result?.Preparation.Errors ?? Array.Empty(), + preparationWarnings = result?.Preparation.Warnings ?? Array.Empty(), + association = result?.Online is null ? null : new + { + status = result.Online.Status.ToString(), + result.Online.AssociationSucceeded, + result.Online.DomainInventorySucceeded, + result.Online.SessionRemainsOpen, + result.Online.Message + }, + domains = result?.Online?.Domains is null ? null : new + { + expected = result.Online.Domains.ExpectedDomains, + observed = result.Online.Domains.ObservedDomains, + matched = result.Online.Domains.MatchedDomains, + missing = result.Online.Domains.MissingExpectedDomains, + extra = result.Online.Domains.ExtraObservedDomains, + result.Online.Domains.IsCompatible, + result.Online.Domains.IsExactMatch, + result.Online.Domains.Summary + }, + initialRead = result?.InitialRead is null ? null : new + { + status = result.InitialRead.Status.ToString(), + result.InitialRead.Message, + result.InitialRead.SuccessfulTargetCount, + result.InitialRead.FailedTargetCount, + result.InitialRead.ProjectedLeafCount, + maximumVariableReferencesPerRead = result.InitialRead.Plan.MaximumVariableReferencesPerRead, + maximumOutstandingReads = result.InitialRead.Plan.MaximumOutstandingReads, + targetCount = result.InitialRead.Plan.Targets.Count, + batchCount = result.InitialRead.Plan.Batches.Count, + batches = result.InitialRead.Batches.Select(batch => new + { + batch.BatchIndex, + targetCount = batch.Targets.Count, + references = batch.Targets.Select(target => target.MmsReference).ToArray(), + successCount = batch.Read.Results.Count(item => item.IsSuccess), + failureCount = batch.Read.Results.Count(item => !item.IsSuccess), + projectionErrorCount = batch.Projections.Sum(item => item.Errors.Count) + }).ToArray() + }, + diagnostic + } + }; + + await WriteEvidenceAsync(command.EvidencePath, evidence, cancellationToken).ConfigureAwait(false); + return new SclSafeTrialRunResult(exitCode, result?.IsSuccess == true, message, command.EvidencePath); + } + + private static async Task WriteInputFailureAsync( + IReadOnlyList args, + string message, + CancellationToken cancellationToken) + { + var path = Path.Combine( + Path.GetTempPath(), + $"ARSAS-SCL-Trial-Invalid-{DateTime.UtcNow:yyyyMMdd-HHmmss}-{Guid.NewGuid():N}.json"); + var evidence = new + { + schema = "arsas-scl-safe-trial-v2", + capturedAtUtc = DateTimeOffset.UtcNow, + success = false, + exitCode = 30, + message, + arguments = args.ToArray() + }; + await WriteEvidenceAsync(path, evidence, cancellationToken).ConfigureAwait(false); + return new SclSafeTrialRunResult(30, false, message, path); + } + + private static async Task WriteEvidenceAsync( + string path, + object evidence, + CancellationToken cancellationToken) + { + var directory = Path.GetDirectoryName(path); + if (!string.IsNullOrWhiteSpace(directory)) + Directory.CreateDirectory(directory); + + var json = JsonSerializer.Serialize(evidence, new JsonSerializerOptions + { + WriteIndented = true + }); + await File.WriteAllTextAsync(path, json, cancellationToken).ConfigureAwait(false); + } +} diff --git a/Services/SmartIedOnboardingBehavior.cs b/Services/SmartIedOnboardingBehavior.cs new file mode 100644 index 000000000..9f58b1c18 --- /dev/null +++ b/Services/SmartIedOnboardingBehavior.cs @@ -0,0 +1,323 @@ +using System.Collections.Specialized; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Windows; +using System.Windows.Controls; +using System.Windows.Controls.Primitives; +using System.Windows.Input; +using System.Windows.Media; +using System.Windows.Threading; +using ArIED61850Tester.Models; + +namespace ArIED61850Tester.Services; + +public sealed record SmartIedBulkActionState( + bool ShowConnectAll, + int TotalDevices, + int CandidateCount, + string Label, + string ToolTip); + +public static class SmartIedBulkActionPolicy +{ + public static SmartIedBulkActionState Evaluate(IEnumerable devices) + { + var snapshot = devices?.ToArray() ?? Array.Empty(); + var candidateCount = snapshot.Count(IsActionableConnectCandidate); + var show = snapshot.Length > 1 && candidateCount > 0; + var label = candidateCount switch + { + <= 0 => "Connect All", + 1 => "Connect 1 IED", + _ => $"Connect {candidateCount} IEDs" + }; + var toolTip = show + ? $"Connect/start the {candidateCount} IED(s) that are ready for a bulk connection. Already monitoring, busy, or endpoint-unbound IEDs are skipped." + : "Bulk connect appears only when multiple IEDs are loaded and at least one has a usable endpoint that still needs connection/monitoring."; + + return new SmartIedBulkActionState(show, snapshot.Length, candidateCount, label, toolTip); + } + + private static bool IsActionableConnectCandidate(Iec61850MonitorDevice device) + => device is not null + && !device.IsBusy + && !device.IsMonitoring + && !string.IsNullOrWhiteSpace(device.IpAddress) + && device.Port is >= 1 and <= 65535; +} + +/// +/// Presentation-only onboarding refinement for the Engineering IED Explorer. +/// Existing Open SCL, IP discovery, and Connect All handlers remain the execution +/// authorities. All visual mutations are marshalled onto the MainWindow dispatcher. +/// +public static class SmartIedOnboardingBehavior +{ + private static readonly ConditionalWeakTable States = new(); + + public static void Install(MainWindow window) + { + ArgumentNullException.ThrowIfNull(window); + var state = States.GetValue(window, static owner => new SmartIedOnboardingState(owner)); + state.InstallOrRefresh(); + } + + private sealed class SmartIedOnboardingState + { + private readonly MainWindow _window; + private readonly HashSet