-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainViewModel.cs
More file actions
1793 lines (1615 loc) · 71.1 KB
/
Copy pathMainViewModel.cs
File metadata and controls
1793 lines (1615 loc) · 71.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System.Collections.ObjectModel;
using System.Collections.Concurrent;
using System.Collections.Specialized;
using System.IO;
using System.Text.Json;
using System.Windows;
using System.Windows.Threading;
using Dnp3MasterTester.Models;
using Dnp3MasterTester.Models.Reports;
using Dnp3MasterTester.Services;
using Dnp3MasterTester.Services.Reports;
using Microsoft.Win32;
namespace Dnp3MasterTester.ViewModels;
public sealed class MainViewModel : ViewModelBase
{
private const int MaxRows = 500;
private const int UiFlushIntervalMs = 250;
private const int ReportSnapshotIntervalMs = 3000;
private const int MaxRowsPerFlush = 40;
private const int UiTransitionFlushPaddingMs = 40;
private readonly IDnp3MasterService _service;
private readonly InternalPdfReportExportService _reportExportService = new();
private readonly Dictionary<string, PointCatalogEntry> _pointCatalog = new(StringComparer.Ordinal);
private readonly JsonSerializerOptions _profileSerializerOptions = new() { WriteIndented = true, PropertyNameCaseInsensitive = true };
private readonly ConcurrentQueue<EventLogEntry> _pendingEventLogs = new();
private readonly ConcurrentQueue<SoeEventRow> _pendingSoeAudit = new();
private readonly ConcurrentQueue<LinkTraceEntry> _pendingLinkTrace = new();
private readonly ConcurrentDictionary<string, ValueViewerRow> _pendingValueRows = new(StringComparer.Ordinal);
private readonly DispatcherTimer _uiFlushTimer;
private readonly DispatcherTimer _transitionFlushTimer;
private string _connectionState = "Idle";
private string _connectionDetail = "Disconnected";
private bool _isBusy;
private bool _isBufferedCollectionUpdate;
private bool _hasBufferedWorkspaceChanges;
private DateTime _heavyUiFlushSuspendedUntilUtc = DateTime.MinValue;
private DateTime _lastReportSnapshotAt = DateTime.MinValue;
private PointCatalogProfile? _selectedPointCatalogProfile;
private PointCatalogEntry? _selectedPointCatalogEntry;
private ushort _commandPointIndex;
private CommandMode _selectedCommandMode = CommandMode.DirectOperate;
private OpType _selectedBinaryOperation = OpType.LatchOn;
private CommandTransaction? _latestCommandTransaction;
private readonly ReportBrandingSettings _reportBranding = new();
private readonly ReportManualAssessment _manualAssessment = new();
private FatTestSessionSnapshot _reportSnapshot = new();
private string _reportPreviewPath = string.Empty;
private string _reportPreviewStatus = "Preview not rendered. Complete report setup and automated testing first.";
private string _guidedTestingProgressStatus = "No guided FAT test is running.";
private ReportWorkspaceStage _reportWorkspaceStage = ReportWorkspaceStage.Identity;
private bool _reportWorkspaceActivated;
private bool _isReportFinalized;
private DateTime? _reportFinalizedAtLocal;
public MainViewModel()
: this(new Dnp3MasterService())
{
}
public MainViewModel(IDnp3MasterService service)
{
_service = service;
Settings = new ConnectionSettings();
PointCatalogProfiles = LoadPointCatalogProfiles();
PointCatalog = new ObservableCollection<PointCatalogEntry>();
SerialPortOptions = new ObservableCollection<string>();
TransportTypes = Enum.GetValues(typeof(DnpTransportType)).Cast<DnpTransportType>().ToArray();
PollingProfiles = Enum.GetValues(typeof(PollingProfileKind)).Cast<PollingProfileKind>().ToArray();
PointTypeOptions = ["Binary Input", "Binary Output", "Binary Output Status", "Analog Input", "Analog Output Status"];
SerialDataBitOptions = Enum.GetValues(typeof(DataBits)).Cast<DataBits>().ToArray();
SerialStopBitOptions = Enum.GetValues(typeof(StopBits)).Cast<StopBits>().ToArray();
SerialParityOptions = Enum.GetValues(typeof(Parity)).Cast<Parity>().ToArray();
SerialFlowControlOptions = Enum.GetValues(typeof(FlowControl)).Cast<FlowControl>().ToArray();
CommandModes = Enum.GetValues(typeof(CommandMode)).Cast<CommandMode>().ToArray();
BinaryOperations = new[] { OpType.LatchOn, OpType.LatchOff, OpType.PulseOn, OpType.PulseOff };
Settings.PropertyChanged += (_, _) =>
{
RaiseConnectionSummaryChanged();
RaisePropertyChanged(nameof(SerialPortAvailabilityText));
if (!IsReportFinalized)
{
RefreshReportSnapshot(force: true);
}
};
ConnectCommand = new RelayCommand(_ => ConnectAsync(), _ => !_isBusy && !_service.IsConnected);
DisconnectCommand = new RelayCommand(_ => DisconnectAsync(), _ => !_isBusy && _service.IsConnected);
IntegrityPollCommand = new RelayCommand(_ => IntegrityPollAsync(), _ => !_isBusy && _service.IsConnected);
EventPollCommand = new RelayCommand(_ => EventPollAsync(), _ => !_isBusy && _service.IsConnected);
LinkStatusCommand = new RelayCommand(_ => CheckLinkAsync(), _ => !_isBusy && _service.IsConnected);
SendBinaryCommand = new RelayCommand(_ => SendBinaryCommandAsync(), _ => !_isBusy && _service.IsConnected);
AddPointCatalogEntryCommand = new RelayCommand(_ => AddPointCatalogEntry(), _ => SelectedPointCatalogProfile is not null);
RemovePointCatalogEntryCommand = new RelayCommand(_ => RemovePointCatalogEntry(), _ => SelectedPointCatalogEntry is not null);
SavePointCatalogProfileCommand = new RelayCommand(_ => SavePointCatalogProfile(), _ => SelectedPointCatalogProfile is not null);
ReloadPointCatalogProfileCommand = new RelayCommand(_ => ReloadPointCatalogProfile(), _ => SelectedPointCatalogProfile is not null);
RefreshSerialPortsCommand = new RelayCommand(_ => RefreshSerialPorts());
RefreshReportSnapshotCommand = new RelayCommand(_ => RefreshReportSnapshotAndPreview(), _ => !IsReportFinalized);
FinalizeReportEvidenceCommand = new RelayCommand(_ => FinalizeReportEvidence(), _ => !IsReportFinalized);
ReopenLiveReportCommand = new RelayCommand(_ => ReopenLiveReport(), _ => IsReportFinalized);
RenderReportPreviewCommand = new RelayCommand(_ => RenderReportPreview());
ExportReportPdfCommand = new RelayCommand(_ => ExportReportPdf());
OpenRenderedPdfCommand = new RelayCommand(_ => OpenRenderedPdf(), _ => File.Exists(ReportPreviewPath));
EditReportSetupCommand = new RelayCommand(_ => ReportWorkspaceStage = ReportWorkspaceStage.Identity);
ContinueReportTestingCommand = new RelayCommand(_ => ContinueReportTesting());
RunAutomatedReportTestingCommand = new RelayCommand(_ => RunAutomatedReportTestingAsync(), _ => !_isBusy && _service.IsConnected);
OpenReportPreviewCommand = new RelayCommand(_ => OpenReportPreview());
GoToBinaryVerificationCommand = new RelayCommand(_ => ReportWorkspaceStage = ReportWorkspaceStage.BinaryVerification);
GoToAnalogVerificationCommand = new RelayCommand(_ => ReportWorkspaceStage = ReportWorkspaceStage.AnalogVerification);
GoToCommandSequenceCommand = new RelayCommand(_ => ReportWorkspaceStage = ReportWorkspaceStage.CommandSequence);
GoToNonOperationRecoveryCommand = new RelayCommand(_ => ReportWorkspaceStage = ReportWorkspaceStage.NonOperationRecovery);
GoToReportSummaryCommand = new RelayCommand(_ => GoToReportSummary());
RunGuidedCommandSequenceCommand = new RelayCommand(_ => RunGuidedCommandSequenceStepAsync(), _ => !_isBusy && _service.IsConnected && GuidedCommandPoints.Any());
RunGuidedNonOperationRecoveryCommand = new RelayCommand(_ => RunGuidedNonOperationRecoveryStepAsync(), _ => !_isBusy && _service.IsConnected);
SelectCompanyLogoCommand = new RelayCommand(_ => SelectReportLogo(isCompanyLogo: true));
SelectCustomerLogoCommand = new RelayCommand(_ => SelectReportLogo(isCompanyLogo: false));
ClearCompanyLogoCommand = new RelayCommand(_ => ClearReportLogo(isCompanyLogo: true), _ => !string.IsNullOrWhiteSpace(CompanyLogoPath));
ClearCustomerLogoCommand = new RelayCommand(_ => ClearReportLogo(isCompanyLogo: false), _ => !string.IsNullOrWhiteSpace(CustomerLogoPath));
MarkBinaryMappingCorrectCommand = new RelayCommand(_ => SetBinaryMappingAssessment(true));
MarkBinaryMappingIncorrectCommand = new RelayCommand(_ => SetBinaryMappingAssessment(false));
ClearBinaryMappingAssessmentCommand = new RelayCommand(_ => SetBinaryMappingAssessment(null));
MarkAnalogValuesCorrectCommand = new RelayCommand(_ => SetAnalogValueAssessment(true));
MarkAnalogValuesIncorrectCommand = new RelayCommand(_ => SetAnalogValueAssessment(false));
ClearAnalogValueAssessmentCommand = new RelayCommand(_ => SetAnalogValueAssessment(null));
RefreshSerialPorts();
SelectedPointCatalogProfile = PointCatalogProfiles.FirstOrDefault();
RefreshReportSnapshot(force: true);
ValueViewer.CollectionChanged += OnWorkspaceCollectionChanged;
EventLogs.CollectionChanged += OnWorkspaceCollectionChanged;
SoeAudit.CollectionChanged += OnWorkspaceCollectionChanged;
LinkTrace.CollectionChanged += OnWorkspaceCollectionChanged;
PointCatalog.CollectionChanged += OnWorkspaceCollectionChanged;
ValueViewer.CollectionChanged += (_, _) =>
{
RaisePropertyChanged(nameof(BinaryValueRows));
RaisePropertyChanged(nameof(AnalogValueRows));
};
PointCatalog.CollectionChanged += (_, _) => RaisePropertyChanged(nameof(GuidedCommandPoints));
_service.ConnectionStateChanged += (_, snapshot) => Dispatch(() =>
{
ConnectionState = snapshot.State;
ConnectionDetail = snapshot.Detail;
RefreshReportSnapshotIfDue();
});
_service.CommandTransactionUpdated += (_, transaction) => Dispatch(() =>
{
LatestCommandTransaction = Enrich(transaction);
ReplaceLifecycle(transaction.Lifecycle);
RefreshReportSnapshotIfDue();
});
_service.EventLogReceived += (_, entry) => _pendingEventLogs.Enqueue(entry);
_service.LinkTraceReceived += (_, entry) => _pendingLinkTrace.Enqueue(entry);
_service.SoeEventReceived += (_, row) => _pendingSoeAudit.Enqueue(row);
_service.ValueReceived += (_, row) => _pendingValueRows[BuildCatalogKey(row.PointType, row.Index)] = row;
_uiFlushTimer = new DispatcherTimer(DispatcherPriority.Background)
{
Interval = TimeSpan.FromMilliseconds(UiFlushIntervalMs)
};
_uiFlushTimer.Tick += (_, _) => FlushBufferedTelemetry();
_transitionFlushTimer = new DispatcherTimer(DispatcherPriority.Background);
_transitionFlushTimer.Tick += (_, _) =>
{
_transitionFlushTimer.Stop();
if (!IsHeavyUiFlushSuspended)
{
FlushBufferedTelemetry();
}
};
_uiFlushTimer.Start();
}
public ConnectionSettings Settings { get; }
public ObservableCollection<PointCatalogProfile> PointCatalogProfiles { get; }
public ObservableCollection<PointCatalogEntry> PointCatalog { get; }
public ObservableCollection<string> SerialPortOptions { get; }
public IReadOnlyList<DnpTransportType> TransportTypes { get; }
public IReadOnlyList<PollingProfileKind> PollingProfiles { get; }
public IReadOnlyList<string> PointTypeOptions { get; }
public IReadOnlyList<DataBits> SerialDataBitOptions { get; }
public IReadOnlyList<StopBits> SerialStopBitOptions { get; }
public IReadOnlyList<Parity> SerialParityOptions { get; }
public IReadOnlyList<FlowControl> SerialFlowControlOptions { get; }
public IReadOnlyList<CommandMode> CommandModes { get; }
public IReadOnlyList<OpType> BinaryOperations { get; }
public ObservableCollection<ValueViewerRow> ValueViewer { get; } = new();
public ObservableCollection<CommandLifecycleEntry> CommandLifecycle { get; } = new();
public ObservableCollection<EventLogEntry> EventLogs { get; } = new();
public ObservableCollection<SoeEventRow> SoeAudit { get; } = new();
public ObservableCollection<LinkTraceEntry> LinkTrace { get; } = new();
public ObservableCollection<EventLogEntry> ReportEvents { get; } = new();
public ObservableCollection<SoeEventRow> ReportSoeEvents { get; } = new();
public ObservableCollection<LinkTraceEntry> ReportTraceEntries { get; } = new();
public FatTestSessionSnapshot ReportSnapshot
{
get => _reportSnapshot;
private set
{
if (SetProperty(ref _reportSnapshot, value))
{
RaiseReportSnapshotChanged();
}
}
}
public bool IsReportFinalized
{
get => _isReportFinalized;
private set
{
if (SetProperty(ref _isReportFinalized, value))
{
RaiseReportSnapshotChanged();
RaiseReportCommandState();
}
}
}
public string ReportPreviewPath
{
get => _reportPreviewPath;
private set => SetProperty(ref _reportPreviewPath, value);
}
public string ReportPreviewStatus
{
get => _reportPreviewStatus;
private set => SetProperty(ref _reportPreviewStatus, value);
}
public ReportWorkspaceStage ReportWorkspaceStage
{
get => _reportWorkspaceStage;
private set
{
if (SetProperty(ref _reportWorkspaceStage, value))
{
_reportWorkspaceActivated = true;
RaiseReportWorkspaceStageChanged();
}
}
}
public string ConnectionProfile => $"{Settings.Transport} / Master {Settings.MasterAddress} / Outstation {Settings.OutstationAddress}";
public string PointCatalogProfileName => SelectedPointCatalogProfile?.Name ?? "No Point Profile";
public string ConnectionTarget => Settings.Transport == DnpTransportType.Serial ? Settings.GetSerialSummary() : Settings.Endpoint;
public string PollingProfile => Settings.GetEffectivePollingProfile().Summary;
public string SerialProfile => Settings.GetSerialSummary();
public string SerialPortAvailabilityText => BuildSerialPortAvailabilityText();
public bool IsTcpTransport => Settings.Transport == DnpTransportType.Tcp;
public bool IsSerialTransport => Settings.Transport == DnpTransportType.Serial;
public string LatestTransactionId => LatestCommandTransaction?.TransactionId ?? "-";
public string LatestTransactionPoint => LatestCommandTransaction?.PointLabel ?? "-";
public string LatestAcceptanceResult => LatestCommandTransaction?.AcceptanceResult ?? "Pending";
public string LatestFeedbackResult => LatestCommandTransaction?.FeedbackResult ?? "Pending";
public string LatestFeedbackEvidence => LatestCommandTransaction?.FeedbackEvidenceText ?? "-";
public string LatestFinalVerdict => LatestCommandTransaction?.FinalVerdict ?? "Idle";
public string LatestPreparedAt => LatestCommandTransaction?.PreparedAtText ?? "-";
public string LatestRequestedAt => LatestCommandTransaction?.RequestedAtText ?? "-";
public string LatestAcceptanceAt => LatestCommandTransaction?.AcceptanceAtText ?? "-";
public string LatestFeedbackAt => LatestCommandTransaction?.FeedbackAtText ?? "-";
public string LatestAcceptanceLatency => LatestCommandTransaction?.AcceptanceLatencyText ?? "-";
public string LatestFeedbackLatency => LatestCommandTransaction?.FeedbackLatencyText ?? "-";
public string LatestFeedbackMatch => LatestCommandTransaction?.FeedbackMatchedText ?? "No";
public int LiveValueCount => ValueViewer.Count;
public int EventLogCount => EventLogs.Count;
public int SoeAuditCount => SoeAudit.Count;
public int LinkTraceCount => LinkTrace.Count;
public int PointCatalogCount => PointCatalog.Count;
public string ReportTitle => "DNP3 Interoperability Test Report";
public string ReportGeneratedAt => DateTime.Now.ToString("yyyy-MM-dd HH:mm");
public string ReportId => ReportSnapshot.ReportId;
public string ReportEvidenceState => ReportSnapshot.EvidenceStateText;
public string ReportFinalizedAt => ReportSnapshot.FinalizedAtText;
public string ReportOverallVerdict => ReportSnapshot.OverallVerdictText;
public string ReportFatExecutionStatus => ReportSnapshot.FatExecutionStatus;
public string ReportTechnicalResult => ReportSnapshot.TechnicalResult;
public string CompanyName
{
get => _reportBranding.CompanyName;
set => SetBrandingValue(_reportBranding.CompanyName, value, next => _reportBranding.CompanyName = next);
}
public string CustomerName
{
get => _reportBranding.CustomerName;
set => SetBrandingValue(_reportBranding.CustomerName, value, next => _reportBranding.CustomerName = next);
}
public string ProjectName
{
get => _reportBranding.ProjectName;
set => SetBrandingValue(_reportBranding.ProjectName, value, next => _reportBranding.ProjectName = next);
}
public string PreparedBy
{
get => _reportBranding.PreparedBy;
set => SetBrandingValue(_reportBranding.PreparedBy, value, next => _reportBranding.PreparedBy = next);
}
public string ReviewedBy
{
get => _reportBranding.ReviewedBy;
set => SetBrandingValue(_reportBranding.ReviewedBy, value, next => _reportBranding.ReviewedBy = next);
}
public string ApprovedBy
{
get => _reportBranding.ApprovedBy;
set => SetBrandingValue(_reportBranding.ApprovedBy, value, next => _reportBranding.ApprovedBy = next);
}
public string ReportFooterText
{
get => _reportBranding.FooterText;
set => SetBrandingValue(_reportBranding.FooterText, value, next => _reportBranding.FooterText = next);
}
public string GuidedTestingProgressStatus
{
get => _guidedTestingProgressStatus;
private set => SetProperty(ref _guidedTestingProgressStatus, value);
}
public string CompanyLogoPath => _reportBranding.CompanyLogoPath;
public string CustomerLogoPath => _reportBranding.CustomerLogoPath;
public string CompanyLogoName => string.IsNullOrWhiteSpace(CompanyLogoPath) ? "No company logo" : Path.GetFileName(CompanyLogoPath);
public string CustomerLogoName => string.IsNullOrWhiteSpace(CustomerLogoPath) ? "No customer logo" : Path.GetFileName(CustomerLogoPath);
public string BinaryIndicationAssessmentText => _manualAssessment.BinaryIndicationMappingVerified switch
{
true => "Binary mapping verified correct",
false => "Binary mapping needs correction",
_ => "Binary mapping not verified"
};
public string BinaryIndicationRemarks
{
get => _manualAssessment.BinaryIndicationRemarks;
set => SetManualAssessmentValue(_manualAssessment.BinaryIndicationRemarks, value, next => _manualAssessment.BinaryIndicationRemarks = next);
}
public string AnalogValueAssessmentText => _manualAssessment.AnalogValueVerificationPassed switch
{
true => "Analog values verified correct",
false => "Analog values need correction",
_ => "Analog values not verified"
};
public string AnalogValueRemarks
{
get => _manualAssessment.AnalogValueRemarks;
set => SetManualAssessmentValue(_manualAssessment.AnalogValueRemarks, value, next => _manualAssessment.AnalogValueRemarks = next);
}
public string CommandSequenceStatus => _manualAssessment.CommandSequenceExecuted
? $"Attempted {_manualAssessment.CommandSequenceAttempted}, completed {_manualAssessment.CommandSequenceCompleted}"
: "Command sequence not executed";
public string CommandSequenceReadinessText
{
get
{
if (!_service.IsConnected)
{
return "Connect to the DUT before running command sequence.";
}
var commandCount = GuidedCommandPoints.Count();
return commandCount == 0
? "No command points are ready. Configure Binary Output rows with feedback mapping in Point Database first."
: $"{commandCount} configured command point(s) ready. The app will send commands one by one with 1 second pacing.";
}
}
public string NonOperationStatus => _manualAssessment.NonOperationTestExecuted
? _manualAssessment.NonOperationRejected ? "Non-operation test passed" : "Non-operation test needs review"
: "Non-operation test not executed";
public string RecoveryStatus => _manualAssessment.RecoveryTestExecuted
? _manualAssessment.RecoveryRestored ? $"Recovery restored in {_manualAssessment.RecoveryDurationSeconds:0.0}s" : "Recovery did not restore communication"
: "Recovery test not executed";
public IEnumerable<ValueViewerRow> BinaryValueRows => ValueViewer.Where(x => x.PointType.Contains("Binary", StringComparison.OrdinalIgnoreCase));
public IEnumerable<ValueViewerRow> AnalogValueRows => ValueViewer.Where(x => x.PointType.Contains("Analog", StringComparison.OrdinalIgnoreCase));
public IEnumerable<PointCatalogEntry> GuidedCommandPoints => PointCatalog.Where(x =>
string.Equals(x.PointType, "Binary Output", StringComparison.OrdinalIgnoreCase) &&
x.FeedbackMappingEnabled &&
x.FeedbackIndex.HasValue);
public string ReportWorkspaceStageText => ReportWorkspaceStage switch
{
ReportWorkspaceStage.Identity => "1. Report Identity",
ReportWorkspaceStage.BinaryVerification => "2. Binary Verification",
ReportWorkspaceStage.AnalogVerification => "3. Analog Verification",
ReportWorkspaceStage.CommandSequence => "4. Command Sequence",
ReportWorkspaceStage.NonOperationRecovery => "5. Non-operation & Recovery",
ReportWorkspaceStage.Summary => "6. Result Summary",
_ => "7. PDF Preview"
};
public Visibility ReportSetupVisibility => ReportWorkspaceStage == ReportWorkspaceStage.Identity ? Visibility.Visible : Visibility.Collapsed;
public Visibility ReportBinaryVisibility => ReportWorkspaceStage == ReportWorkspaceStage.BinaryVerification ? Visibility.Visible : Visibility.Collapsed;
public Visibility ReportAnalogVisibility => ReportWorkspaceStage == ReportWorkspaceStage.AnalogVerification ? Visibility.Visible : Visibility.Collapsed;
public Visibility ReportCommandSequenceVisibility => ReportWorkspaceStage == ReportWorkspaceStage.CommandSequence ? Visibility.Visible : Visibility.Collapsed;
public Visibility ReportNonOperationRecoveryVisibility => ReportWorkspaceStage == ReportWorkspaceStage.NonOperationRecovery ? Visibility.Visible : Visibility.Collapsed;
public Visibility ReportTestingVisibility => ReportWorkspaceStage is ReportWorkspaceStage.BinaryVerification or ReportWorkspaceStage.AnalogVerification or ReportWorkspaceStage.CommandSequence or ReportWorkspaceStage.NonOperationRecovery or ReportWorkspaceStage.Summary ? Visibility.Visible : Visibility.Collapsed;
public Visibility ReportSummaryVisibility => ReportWorkspaceStage == ReportWorkspaceStage.Summary ? Visibility.Visible : Visibility.Collapsed;
public Visibility ReportPreviewVisibility => ReportWorkspaceStage == ReportWorkspaceStage.Preview ? Visibility.Visible : Visibility.Collapsed;
public Visibility ReportPrePreviewVisibility => ReportWorkspaceStage == ReportWorkspaceStage.Preview ? Visibility.Collapsed : Visibility.Visible;
public int ReportFatItemCount => ReportSnapshot.FatItems.Count;
public int ReportExecutedItemCount => ReportSnapshot.ExecutedItemCount;
public int ReportPassCount => ReportSnapshot.PassedItemCount;
public int ReportWarningCount => ReportSnapshot.WarningItemCount;
public int ReportFailCount => ReportSnapshot.FailedItemCount;
public int ReportOpenItemCount => ReportSnapshot.OpenItemCount;
public string LatestEventSummary
{
get
{
var row = EventLogs.LastOrDefault();
if (row is null)
{
return "No SCADA events captured yet.";
}
return !string.IsNullOrWhiteSpace(row.Detail)
? row.Detail
: row.EventType;
}
}
public string LatestSoeSummary
{
get
{
var row = SoeAudit.LastOrDefault();
return row is null
? "No SOE callbacks captured yet."
: $"{row.SourceTimestampText} - {row.PointLabel} = {row.Value}";
}
}
public string LatestTraceSummary => LinkTrace.LastOrDefault()?.Summary ?? "No protocol trace records yet.";
public RelayCommand ConnectCommand { get; }
public RelayCommand DisconnectCommand { get; }
public RelayCommand IntegrityPollCommand { get; }
public RelayCommand EventPollCommand { get; }
public RelayCommand LinkStatusCommand { get; }
public RelayCommand SendBinaryCommand { get; }
public RelayCommand AddPointCatalogEntryCommand { get; }
public RelayCommand RemovePointCatalogEntryCommand { get; }
public RelayCommand SavePointCatalogProfileCommand { get; }
public RelayCommand ReloadPointCatalogProfileCommand { get; }
public RelayCommand RefreshSerialPortsCommand { get; }
public RelayCommand RefreshReportSnapshotCommand { get; }
public RelayCommand FinalizeReportEvidenceCommand { get; }
public RelayCommand ReopenLiveReportCommand { get; }
public RelayCommand RenderReportPreviewCommand { get; }
public RelayCommand ExportReportPdfCommand { get; }
public RelayCommand OpenRenderedPdfCommand { get; }
public RelayCommand SelectCompanyLogoCommand { get; }
public RelayCommand SelectCustomerLogoCommand { get; }
public RelayCommand ClearCompanyLogoCommand { get; }
public RelayCommand ClearCustomerLogoCommand { get; }
public RelayCommand MarkBinaryMappingCorrectCommand { get; }
public RelayCommand MarkBinaryMappingIncorrectCommand { get; }
public RelayCommand ClearBinaryMappingAssessmentCommand { get; }
public RelayCommand MarkAnalogValuesCorrectCommand { get; }
public RelayCommand MarkAnalogValuesIncorrectCommand { get; }
public RelayCommand ClearAnalogValueAssessmentCommand { get; }
public RelayCommand EditReportSetupCommand { get; }
public RelayCommand ContinueReportTestingCommand { get; }
public RelayCommand RunAutomatedReportTestingCommand { get; }
public RelayCommand OpenReportPreviewCommand { get; }
public RelayCommand GoToBinaryVerificationCommand { get; }
public RelayCommand GoToAnalogVerificationCommand { get; }
public RelayCommand GoToCommandSequenceCommand { get; }
public RelayCommand GoToNonOperationRecoveryCommand { get; }
public RelayCommand GoToReportSummaryCommand { get; }
public RelayCommand RunGuidedCommandSequenceCommand { get; }
public RelayCommand RunGuidedNonOperationRecoveryCommand { get; }
public string ConnectionState
{
get => _connectionState;
private set => SetProperty(ref _connectionState, value);
}
public string ConnectionDetail
{
get => _connectionDetail;
private set => SetProperty(ref _connectionDetail, value);
}
public bool IsBusy
{
get => _isBusy;
private set
{
if (SetProperty(ref _isBusy, value))
{
RaiseCommandState();
}
}
}
public ushort CommandPointIndex
{
get => _commandPointIndex;
set => SetProperty(ref _commandPointIndex, value);
}
public CommandMode SelectedCommandMode
{
get => _selectedCommandMode;
set => SetProperty(ref _selectedCommandMode, value);
}
public OpType SelectedBinaryOperation
{
get => _selectedBinaryOperation;
set => SetProperty(ref _selectedBinaryOperation, value);
}
public CommandTransaction? LatestCommandTransaction
{
get => _latestCommandTransaction;
private set
{
if (SetProperty(ref _latestCommandTransaction, value))
{
RaisePropertyChanged(nameof(LatestTransactionId));
RaisePropertyChanged(nameof(LatestTransactionPoint));
RaisePropertyChanged(nameof(LatestAcceptanceResult));
RaisePropertyChanged(nameof(LatestFeedbackResult));
RaisePropertyChanged(nameof(LatestFeedbackEvidence));
RaisePropertyChanged(nameof(LatestFinalVerdict));
RaisePropertyChanged(nameof(LatestPreparedAt));
RaisePropertyChanged(nameof(LatestRequestedAt));
RaisePropertyChanged(nameof(LatestAcceptanceAt));
RaisePropertyChanged(nameof(LatestFeedbackAt));
RaisePropertyChanged(nameof(LatestAcceptanceLatency));
RaisePropertyChanged(nameof(LatestFeedbackLatency));
RaisePropertyChanged(nameof(LatestFeedbackMatch));
}
}
}
public PointCatalogProfile? SelectedPointCatalogProfile
{
get => _selectedPointCatalogProfile;
set
{
if (SetProperty(ref _selectedPointCatalogProfile, value))
{
ApplyPointCatalogProfile(value);
RaisePropertyChanged(nameof(PointCatalogProfileName));
RefreshNamedSurfaces();
RefreshReportSnapshot(force: true);
RaisePointCatalogCommandState();
}
}
}
public PointCatalogEntry? SelectedPointCatalogEntry
{
get => _selectedPointCatalogEntry;
set
{
if (SetProperty(ref _selectedPointCatalogEntry, value))
{
RaisePointCatalogCommandState();
}
}
}
private Task ConnectAsync() => RunBusyAsync(async () =>
{
var validationErrors = Settings.Validate();
if (validationErrors.Count != 0)
{
var detail = string.Join(" ", validationErrors);
ConnectionState = "Invalid Settings";
ConnectionDetail = detail;
AppendBottom(EventLogs, new EventLogEntry
{
TimestampLocal = DateTime.Now,
EventType = "Validation Error",
Source = "UI",
Detail = detail,
Status = "Blocked"
});
return;
}
await _service.ConnectAsync(Settings);
});
private Task DisconnectAsync() => RunBusyAsync(_service.DisconnectAsync);
private Task IntegrityPollAsync() => RunBusyAsync(_service.RunIntegrityPollAsync);
private Task EventPollAsync() => RunBusyAsync(_service.DemandEventPollAsync);
private Task CheckLinkAsync() => RunBusyAsync(_service.CheckLinkStatusAsync);
private Task SendBinaryCommandAsync() => RunBusyAsync(async () =>
{
var index = CommandPointIndex;
var mode = SelectedCommandMode;
var operation = SelectedBinaryOperation;
var preparedAt = DateTime.Now;
AppendBottom(EventLogs, new EventLogEntry
{
TimestampLocal = preparedAt,
EventType = "Command Prepared",
Source = "UI",
PointType = "Binary Output",
Index = index,
RawValue = operation.ToString(),
Value = operation.ToString(),
Status = mode.ToString(),
SourceReason = SourceReason.CommandResponse,
Detail = $"Operator issued binary control request for index {index}: {mode} / {operation}"
});
var mapping = FindCommandMapping(index, "Binary Output");
await _service.ExecuteBinaryControlAsync(
index,
mode,
operation,
preparedAt,
mapping?.FeedbackPointType,
mapping?.FeedbackIndex,
mapping?.TimeoutMs);
});
private async Task RunBusyAsync(Func<Task> action)
{
try
{
IsBusy = true;
await action();
}
catch (Exception ex)
{
AppendBottom(EventLogs, new EventLogEntry
{
TimestampLocal = DateTime.Now,
EventType = "UI Error",
Source = "UI",
Detail = ex.Message,
Status = "Error"
});
}
finally
{
IsBusy = false;
RaiseCommandState();
}
}
private void UpsertValue(ValueViewerRow row)
{
var existing = ValueViewer.FirstOrDefault(x => x.PointType == row.PointType && x.Index == row.Index);
if (existing is null)
{
InsertTop(ValueViewer, row);
return;
}
existing.Value = row.Value;
existing.Flags = row.Flags;
existing.ReceivedAtLocal = row.ReceivedAtLocal;
existing.DisplayName = row.DisplayName;
existing.ScadaTag = row.ScadaTag;
existing.RawValue = row.RawValue;
// Preserve the last valid event timestamp when a later static/integrity refresh
// re-reports the same value without time information.
if (ShouldPreserveTimestampEvidence(existing, row))
{
existing.Quality = existing.Quality;
existing.SourceTimestampLocal = existing.SourceTimestampLocal;
existing.SourceTimestampKind = existing.SourceTimestampKind;
existing.Source = existing.Source;
existing.SourceReason = existing.SourceReason;
}
else
{
existing.Quality = row.Quality;
existing.SourceTimestampLocal = row.SourceTimestampLocal;
existing.SourceTimestampKind = row.SourceTimestampKind;
existing.Source = row.Source;
existing.SourceReason = row.SourceReason;
}
var index = ValueViewer.IndexOf(existing);
if (index > 0)
{
ValueViewer.Move(index, 0);
}
}
private static bool ShouldPreserveTimestampEvidence(ValueViewerRow existing, ValueViewerRow incoming)
{
if (existing.SourceTimestampKind != SourceTimestampKind.Valid)
{
return false;
}
if (incoming.SourceTimestampKind == SourceTimestampKind.Valid)
{
return false;
}
if (!string.Equals(existing.Value, incoming.Value, StringComparison.Ordinal))
{
return false;
}
return incoming.SourceReason is SourceReason.StartupIntegrity
or SourceReason.ManualIntegrity
or SourceReason.PeriodicStaticRefresh;
}
private static void InsertTop<T>(ObservableCollection<T> items, T item)
{
items.Insert(0, item);
while (items.Count > MaxRows)
{
items.RemoveAt(items.Count - 1);
}
}
private static void AppendBottom<T>(ObservableCollection<T> items, T item)
{
items.Add(item);
while (items.Count > MaxRows)
{
items.RemoveAt(0);
}
}
public void SuspendHeavyUiFlush(TimeSpan duration)
{
if (duration <= TimeSpan.Zero)
{
return;
}
var untilUtc = DateTime.UtcNow.Add(duration);
if (untilUtc > _heavyUiFlushSuspendedUntilUtc)
{
_heavyUiFlushSuspendedUntilUtc = untilUtc;
}
_transitionFlushTimer.Stop();
_transitionFlushTimer.Interval = duration + TimeSpan.FromMilliseconds(UiTransitionFlushPaddingMs);
_transitionFlushTimer.Start();
}
private bool IsHeavyUiFlushSuspended => DateTime.UtcNow < _heavyUiFlushSuspendedUntilUtc;
private void FlushBufferedTelemetry()
{
if (Application.Current?.Dispatcher.HasShutdownStarted == true ||
Application.Current?.Dispatcher.HasShutdownFinished == true)
{
_uiFlushTimer.Stop();
_transitionFlushTimer.Stop();
return;
}
if (IsHeavyUiFlushSuspended)
{
return;
}
var hadChanges = false;
_isBufferedCollectionUpdate = true;
try
{
hadChanges |= FlushLatestValues();
hadChanges |= FlushQueue(_pendingEventLogs, EventLogs, Enrich);
hadChanges |= FlushQueue(_pendingSoeAudit, SoeAudit, Enrich);
hadChanges |= FlushQueue(_pendingLinkTrace, LinkTrace, static row => row);
}
finally
{
_isBufferedCollectionUpdate = false;
}
if (hadChanges || _hasBufferedWorkspaceChanges)
{
_hasBufferedWorkspaceChanges = false;
RaiseWorkspaceSummaryChanged();
RefreshReportSnapshotIfDue();
}
}
private void RefreshReportSnapshotIfDue()
{
if (!ShouldAutoRefreshReportSnapshot())
{
return;
}
var now = DateTime.UtcNow;
if ((now - _lastReportSnapshotAt).TotalMilliseconds < ReportSnapshotIntervalMs)
{
return;
}
_lastReportSnapshotAt = now;
ReplaceSnapshot(ReportEvents, TakeLatest(EventLogs, 8));
ReplaceSnapshot(ReportSoeEvents, TakeLatest(SoeAudit, 8));
ReplaceSnapshot(ReportTraceEntries, TakeLatest(LinkTrace, 6));
RefreshReportSnapshot(force: false);
}
private void RefreshReportSnapshot(bool force)
{
if (!force && IsReportFinalized)
{
return;
}
if (!force && !ShouldAutoRefreshReportSnapshot())
{
return;
}
if (force)
{
ReplaceSnapshot(ReportEvents, TakeLatest(EventLogs, 8));
ReplaceSnapshot(ReportSoeEvents, TakeLatest(SoeAudit, 8));
ReplaceSnapshot(ReportTraceEntries, TakeLatest(LinkTrace, 6));
}
ReportSnapshot = FatReportSnapshotBuilder.Build(
_reportBranding,
Settings,
PointCatalogProfileName,
ConnectionState,
ConnectionDetail,
ValueViewer.ToArray(),
EventLogs.ToArray(),
SoeAudit.ToArray(),
LinkTrace.ToArray(),
LatestCommandTransaction,
_manualAssessment,
IsReportFinalized,
string.IsNullOrWhiteSpace(ReportSnapshot.ReportId) ? null : ReportSnapshot.ReportId,
_reportFinalizedAtLocal);
}
private void RefreshReportSnapshotAndPreview()
{
_reportWorkspaceActivated = true;
RefreshReportSnapshot(force: true);
ReportPreviewStatus = "Snapshot refreshed. Render preview after automated testing.";
}
private void FinalizeReportEvidence()
{
_reportFinalizedAtLocal = DateTime.Now;
IsReportFinalized = true;
RefreshReportSnapshot(force: true);
RenderReportPreview(refreshSnapshot: false);
ReportWorkspaceStage = ReportWorkspaceStage.Preview;
AppendBottom(EventLogs, new EventLogEntry
{
TimestampLocal = DateTime.Now,
EventType = "Report Finalized",
Source = "Report Workspace",
Status = ReportSnapshot.OverallVerdictText,
Detail = $"Evidence snapshot {ReportSnapshot.ReportId} frozen with {ReportSnapshot.FatItems.Count} FAT items."
});
}
private void ReopenLiveReport()
{
_reportFinalizedAtLocal = null;
IsReportFinalized = false;
RefreshReportSnapshot(force: true);
ReportWorkspaceStage = ReportWorkspaceStage.Identity;
ReportPreviewStatus = "Report reopened for editing. Render preview after reviewing setup and testing.";
AppendBottom(EventLogs, new EventLogEntry
{
TimestampLocal = DateTime.Now,
EventType = "Report Reopened",
Source = "Report Workspace",
Status = "Live",
Detail = $"Evidence snapshot {ReportSnapshot.ReportId} returned to live preview mode."
});
}
private void RenderReportPreview(bool refreshSnapshot = true)
{
try
{
if (refreshSnapshot)
{
RefreshReportSnapshot(force: true);
}
ReportPreviewPath = _reportExportService.RenderPreview(ReportSnapshot);
ReportPreviewStatus = $"Rendered {Path.GetFileName(ReportPreviewPath)} at {DateTime.Now:HH:mm:ss}.";
OpenRenderedPdfCommand.RaiseCanExecuteChanged();
}
catch (Exception ex)
{
ReportPreviewStatus = $"PDF preview failed: {ex.Message}";
AppendBottom(EventLogs, new EventLogEntry
{
TimestampLocal = DateTime.Now,
EventType = "Report Preview Error",
Source = "Report Workspace",
Status = "Error",
Detail = ex.Message
});
}
}
private void ContinueReportTesting()
{
_reportWorkspaceActivated = true;
RefreshReportSnapshot(force: true);
ReportWorkspaceStage = ReportWorkspaceStage.BinaryVerification;
ReportPreviewStatus = "Report identity saved. Verify binary and analog values before automated command/recovery tests.";
}
private Task RunAutomatedReportTestingAsync() => RunBusyAsync(async () =>
{
AppendBottom(EventLogs, new EventLogEntry
{
TimestampLocal = DateTime.Now,
EventType = "Automated FAT Test Started",
Source = "Report Workspace",
Status = "Running",
Detail = "Running link check, integrity poll, event poll, configured command sequence, non-operation, and recovery tests."
});
await _service.CheckLinkStatusAsync();
await _service.RunIntegrityPollAsync();
await _service.DemandEventPollAsync();
await RunGuidedCommandSequenceAsync();
await RunGuidedNonOperationTestAsync();
await RunGuidedRecoveryTestAsync();
FlushBufferedTelemetry();
RefreshReportSnapshot(force: true);
ReportWorkspaceStage = ReportWorkspaceStage.Summary;
AppendBottom(EventLogs, new EventLogEntry
{
TimestampLocal = DateTime.Now,
EventType = "Automated FAT Test Completed",
Source = "Report Workspace",
Status = ReportSnapshot.OverallVerdictText,
Detail = $"Automated evidence collection completed for {ReportSnapshot.ReportId}."
});
});
private void OpenReportPreview()
{
_reportWorkspaceActivated = true;
RefreshReportSnapshot(force: true);
RenderReportPreview(refreshSnapshot: false);
ReportWorkspaceStage = ReportWorkspaceStage.Preview;
}
private void OpenRenderedPdf()
{
if (!File.Exists(ReportPreviewPath))
{
ReportPreviewStatus = "PDF file is not available. Render the preview first.";
return;
}
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo
{
FileName = ReportPreviewPath,
UseShellExecute = true
});
}
private void GoToReportSummary()
{
_reportWorkspaceActivated = true;
RefreshReportSnapshot(force: true);
ReportWorkspaceStage = ReportWorkspaceStage.Summary;
}
private bool ShouldAutoRefreshReportSnapshot() =>
_reportWorkspaceActivated &&
!IsReportFinalized &&
ReportWorkspaceStage != ReportWorkspaceStage.Preview;
private async Task RunGuidedCommandSequenceAsync()
{
var commandPoints = GuidedCommandPoints.ToArray();
_manualAssessment.CommandSequenceAttempted = commandPoints.Length;
_manualAssessment.CommandSequenceCompleted = 0;
_manualAssessment.CommandSequenceExecuted = commandPoints.Length > 0;
if (commandPoints.Length == 0)
{