-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMainWindow.RcbExport.cs
More file actions
372 lines (339 loc) · 17.8 KB
/
Copy pathMainWindow.RcbExport.cs
File metadata and controls
372 lines (339 loc) · 17.8 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
using AR.Iec61850.Discovery;
using AR.Iec61850.Mms;
using AR.Iec61850.Scl.Export;
using ArIED61850Tester.Models;
using System.Windows;
namespace ArIED61850Tester;
public partial class MainWindow
{
private readonly Services.RcbAvailabilityProbeService _rcbAvailabilityProbe = new();
private void IedEditRcb_Click(object sender, RoutedEventArgs e)
{
if (!TryGetDeviceFromButton(sender, out var device) || device.IsBusy || device.IsDemo)
return;
SclReportControlInventoryResult? sourceInventory = null;
Exception? sourceInspectionError = null;
MmsRcbAvailabilityResult? latestAvailability = null;
if (!string.IsNullOrWhiteSpace(device.SclSourcePath) && File.Exists(device.SclSourcePath))
{
try
{
sourceInventory = SclReportControlFilter.InspectFile(
device.SclSourcePath,
EffectiveSclIedName(device),
device.SclAccessPointName);
}
catch (Exception ex)
{
sourceInspectionError = ex;
AddLog("WARN", "RCB Export", $"{device.Name}: source SCL RCB inventory failed: {ex.Message}");
}
}
var rows = BuildRcbExportRows(device, sourceInventory, availability: null);
if (rows.Count == 0)
{
var detail = sourceInspectionError?.Message ??
"No Report Control Blocks are available in the opened SCL or last successful live discovery model.";
MessageBox.Show(this, detail, "RCB Export Filter", MessageBoxButton.OK, MessageBoxImage.Information);
SetStatus($"{device.Name}: no RCB inventory is available for legacy SAS export.");
return;
}
SelectedDevice = device;
var options = new RcbExportWindowOptions
{
IedName = device.Name,
Endpoint = device.EndpointText,
IsMock = false,
CanCheckAvailability = device.IsConnected,
Rows = rows,
RefreshAvailabilityAsync = device.IsConnected
? async cancellationToken =>
{
latestAvailability = await _rcbAvailabilityProbe.CheckAsync(device, cancellationToken).ConfigureAwait(false);
return BuildRcbExportRows(device, sourceInventory, latestAvailability);
}
: null,
ExportAsync = (row, schema, outputPath, cancellationToken) =>
ExportLegacySasRcbAsync(device, row, schema, outputPath, latestAvailability, cancellationToken)
};
var dialog = new RcbExportFilterWindow(options)
{
Owner = this,
ShowInTaskbar = false,
WindowStartupLocation = WindowStartupLocation.CenterOwner
};
dialog.ShowDialog();
}
private static IReadOnlyList<RcbExportRow> BuildRcbExportRows(
Iec61850MonitorDevice device,
SclReportControlInventoryResult? sourceInventory,
MmsRcbAvailabilityResult? availability)
{
if (sourceInventory != null)
return BuildSourceBackedRcbRows(device, sourceInventory, availability);
return BuildLiveModelRcbRows(device.LiveDiscoveryModel, availability);
}
private static IReadOnlyList<RcbExportRow> BuildSourceBackedRcbRows(
Iec61850MonitorDevice device,
SclReportControlInventoryResult inventory,
MmsRcbAvailabilityResult? availability)
{
var rows = new List<RcbExportRow>();
var mappedKeys = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
if (availability != null)
{
foreach (var snapshot in availability.ReportControls)
{
var descriptor = FindSourceDescriptor(snapshot, inventory.ReportControls);
if (descriptor == null) continue;
mappedKeys.Add(descriptor.SelectionKey);
rows.Add(CreateSourceBackedRow(descriptor, snapshot));
}
}
foreach (var descriptor in inventory.ReportControls)
{
if (mappedKeys.Contains(descriptor.SelectionKey)) continue;
rows.Add(CreateSourceBackedRow(descriptor, snapshot: null, device.IsConnected));
}
return rows;
}
private static RcbExportRow CreateSourceBackedRow(
SclReportControlDescriptor descriptor,
MmsRcbAvailabilitySnapshot? snapshot,
bool connected = true)
{
var memberCount = snapshot?.DataSetMemberCount > 0 ? snapshot.DataSetMemberCount : descriptor.DataSetMemberCount;
var availability = snapshot?.Availability ??
(!descriptor.DataSetResolved
? MmsRcbOperationalAvailability.NoDataSet
: descriptor.DataSetMemberCount == 0
? MmsRcbOperationalAvailability.DataSetEmpty
: MmsRcbOperationalAvailability.Unknown);
var reason = snapshot?.Reason ??
(!descriptor.DataSetResolved
? "The SCL ReportControl does not resolve a DataSet in the same Logical Node."
: descriptor.DataSetMemberCount == 0
? "The SCL ReportControl references an empty DataSet."
: connected
? "Press Check Availability to read RptEna, reservation, Owner, and the live DataSet directory."
: "Offline SCL inventory only. Connect the IED to prove live RCB ownership state.");
return new RcbExportRow
{
SourceSelectionKey = descriptor.SelectionKey,
ExportName = snapshot?.Name ?? descriptor.Name,
Name = snapshot?.Name ?? descriptor.Name,
Reference = snapshot?.Reference ?? descriptor.DisplayReference,
Type = descriptor.Type,
Buffered = descriptor.Buffered,
DataSetName = string.IsNullOrWhiteSpace(descriptor.DataSetName) ? "—" : descriptor.DataSetName,
DataSetReference = snapshot?.DataSetReference ?? descriptor.DataSetReference,
DataSetDetail = descriptor.DataSetResolved
? $"Static DataSet • source model{(descriptor.Indexed ? $" • indexed ×{descriptor.InstanceCount}" : string.Empty)}"
: "Unresolved DataSet",
MemberCount = memberCount,
Availability = availability,
Confidence = snapshot?.Confidence ?? MmsRcbAvailabilityConfidence.Unknown,
StatusText = snapshot == null && availability == MmsRcbOperationalAvailability.Unknown
? "Not checked"
: RcbExportRow.ToStatusText(availability),
Reason = reason,
Owner = snapshot?.Owner ?? string.Empty,
IsSourceBacked = true,
IsIndexedSource = descriptor.Indexed
};
}
private static SclReportControlDescriptor? FindSourceDescriptor(
MmsRcbAvailabilitySnapshot snapshot,
IReadOnlyList<SclReportControlDescriptor> descriptors)
{
var modeMatches = descriptors.Where(descriptor => descriptor.Buffered == snapshot.Buffered).ToArray();
var exact = modeMatches.Where(descriptor =>
descriptor.Name.Equals(snapshot.Name, StringComparison.OrdinalIgnoreCase) &&
LogicalScopeMatches(descriptor, snapshot))
.ToArray();
if (exact.Length == 1) return exact[0];
var indexed = modeMatches.Where(descriptor =>
descriptor.Indexed && IsIndexedRuntimeName(descriptor.Name, snapshot.Name) &&
LogicalScopeMatches(descriptor, snapshot))
.ToArray();
if (indexed.Length == 1) return indexed[0];
var dataSetName = LastReferenceSegment(snapshot.DataSetReference);
var byDataSet = modeMatches.Where(descriptor =>
descriptor.DataSetName.Equals(dataSetName, StringComparison.OrdinalIgnoreCase) &&
LogicalScopeMatches(descriptor, snapshot))
.ToArray();
return byDataSet.Length == 1 ? byDataSet[0] : null;
}
private static bool LogicalScopeMatches(SclReportControlDescriptor descriptor, MmsRcbAvailabilitySnapshot snapshot)
{
var logicalNodeMatches = string.IsNullOrWhiteSpace(snapshot.LogicalNode) ||
descriptor.LogicalNodePath.Equals(snapshot.LogicalNode, StringComparison.OrdinalIgnoreCase);
var logicalDeviceMatches = string.IsNullOrWhiteSpace(snapshot.Domain) ||
string.IsNullOrWhiteSpace(descriptor.LogicalDeviceInstance) ||
snapshot.Domain.EndsWith(descriptor.LogicalDeviceInstance, StringComparison.OrdinalIgnoreCase);
return logicalNodeMatches && logicalDeviceMatches;
}
private static bool IsIndexedRuntimeName(string sourceName, string runtimeName)
{
if (!runtimeName.StartsWith(sourceName, StringComparison.OrdinalIgnoreCase)) return false;
var suffix = runtimeName[sourceName.Length..];
return suffix.Length > 0 && suffix.All(char.IsDigit);
}
private static IReadOnlyList<RcbExportRow> BuildLiveModelRcbRows(
LiveIedModelDiscoveryDocument? model,
MmsRcbAvailabilityResult? availability)
{
if (model == null) return Array.Empty<RcbExportRow>();
var snapshots = availability?.ReportControls
.GroupBy(snapshot => NormalizeRcbReference(snapshot.Reference), StringComparer.OrdinalIgnoreCase)
.ToDictionary(group => group.Key, group => group.First(), StringComparer.OrdinalIgnoreCase)
?? new Dictionary<string, MmsRcbAvailabilitySnapshot>(StringComparer.OrdinalIgnoreCase);
var dataSets = model.DataSets
.GroupBy(dataSet => NormalizeRcbReference(dataSet.Reference), StringComparer.OrdinalIgnoreCase)
.ToDictionary(group => group.Key, group => group.First(), StringComparer.OrdinalIgnoreCase);
var rows = new List<RcbExportRow>();
foreach (var reportControl in model.ReportControls)
{
snapshots.TryGetValue(NormalizeRcbReference(reportControl.Reference), out var snapshot);
dataSets.TryGetValue(NormalizeRcbReference(reportControl.DataSetReference), out var dataSet);
var members = snapshot?.DataSetMemberCount > 0 ? snapshot.DataSetMemberCount : dataSet?.MemberCount ?? 0;
var availabilityState = snapshot?.Availability ??
(string.IsNullOrWhiteSpace(reportControl.DataSetReference)
? MmsRcbOperationalAvailability.NoDataSet
: members == 0 ? MmsRcbOperationalAvailability.DataSetEmpty : MmsRcbOperationalAvailability.Unknown);
rows.Add(new RcbExportRow
{
ExportName = reportControl.Name,
Name = reportControl.Name,
Reference = reportControl.Reference,
Type = reportControl.Buffered ? "Buffered" : "Unbuffered",
Buffered = reportControl.Buffered,
DataSetName = string.IsNullOrWhiteSpace(dataSet?.Name)
? LastReferenceSegment(reportControl.DataSetReference)
: dataSet.Name,
DataSetReference = reportControl.DataSetReference,
DataSetDetail = snapshot?.DataSetDirectorySuccess == true
? "Static DataSet • live directory verified"
: dataSet == null ? "Unresolved DataSet" : "Static DataSet • live discovery",
MemberCount = members,
Availability = availabilityState,
Confidence = snapshot?.Confidence ?? MmsRcbAvailabilityConfidence.Unknown,
StatusText = snapshot == null && availabilityState == MmsRcbOperationalAvailability.Unknown
? "Not checked"
: RcbExportRow.ToStatusText(availabilityState),
Reason = snapshot?.Reason ??
(members > 0 ? "Press Check Availability to prove RptEna and reservation state."
: "The live model does not expose a populated DataSet for this RCB."),
Owner = snapshot?.Owner ?? string.Empty,
IsSourceBacked = false
});
}
return rows;
}
private async Task<RcbExportCompletion> ExportLegacySasRcbAsync(
Iec61850MonitorDevice device,
RcbExportRow row,
SclSchemaProfile schema,
string outputPath,
MmsRcbAvailabilityResult? availability,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();
if (row.MemberCount <= 0)
throw new InvalidOperationException("The selected RCB has no populated DataSet.");
if (row.IsSourceBacked && !string.IsNullOrWhiteSpace(device.SclSourcePath) && File.Exists(device.SclSourcePath))
{
var result = await Task.Run(() => LegacySasSclExporter.WriteFiles(
device.SclSourcePath,
outputPath,
new LegacySasSclExportOptions
{
IedName = EffectiveSclIedName(device),
AccessPointName = device.SclAccessPointName,
SchemaProfile = schema,
SelectedReportControl = new SclReportControlSelection(row.SourceSelectionKey, row.ExportName),
RemoveUnreferencedDataSets = false,
ToolId = "ARIEC61850"
}), cancellationToken);
AddLog("INFO", "RCB Export",
$"{device.Name}: legacy SAS CID saved; schema={result.SclSchema}; RCB={result.RetainedReportControlReference}; DataSet={result.RetainedDataSetName}; members={result.RetainedDataSetMemberCount}; removed RCB={result.RemovedReportControlCount}; output={result.OutputPath}");
SetStatus($"{device.Name}: legacy SAS CID exported with one RCB — {row.Name}.");
return new RcbExportCompletion
{
OutputPath = result.OutputPath,
ReportPath = result.ReportPath,
SummaryPath = result.SummaryPath,
SchemaDisplayName = result.SclSchema,
RetainedReportControl = result.RetainedReportControlReference,
DataSetName = result.RetainedDataSetName,
DataSetMemberCount = result.RetainedDataSetMemberCount,
RemovedReportControlCount = result.RemovedReportControlCount,
Message = $"Export complete: {result.RetainedReportControlReference} is the only RCB in the generated CID."
};
}
var liveModel = device.LiveDiscoveryModel
?? throw new InvalidOperationException("A source SCL file or complete live discovery model is required for legacy SAS export.");
var selectedDataSet = liveModel.DataSets.FirstOrDefault(dataSet =>
NormalizeRcbReference(dataSet.Reference)
.Equals(NormalizeRcbReference(row.DataSetReference), StringComparison.OrdinalIgnoreCase));
var exportModel = liveModel;
if (selectedDataSet is null || selectedDataSet.Members.Count == 0)
{
if (availability is null)
{
throw new InvalidOperationException(
"The live discovery model does not contain FCDA member references for this DataSet. Click Check Availability, wait for the read-only audit to finish, then export again.");
}
exportModel = LiveRcbDataSetEvidenceMerger.MergeSelectedDataSetDirectory(
liveModel,
row.Reference,
availability);
}
if (availability != null)
{
exportModel = LiveRcbDataSetEvidenceMerger.MergeSelectedReportControlEvidence(
exportModel,
row.Reference,
availability);
}
var filteredModel = SclReportControlFilter.FilterLiveModel(exportModel, row.Reference);
var liveResult = await Task.Run(() => AuthoritativeLiveIedSclExporter.WriteFiles(
filteredModel,
outputPath,
new LiveIedSclExportOptions
{
Profile = "full-model",
SchemaProfile = schema,
IpAddress = device.IpAddress,
IedNameOverride = device.Name,
IncludeLowConfidenceTypes = true,
IncludeRuntimeStateComment = false
}), cancellationToken);
var removedCount = Math.Max(0, liveModel.ReportControls.Count - 1);
AddLog("INFO", "RCB Export",
$"{device.Name}: live-model legacy SAS CID saved; schema={liveResult.SclSchema}; RCB={row.Reference}; DataSet={row.DataSetName}; members={row.MemberCount}; removed RCB={removedCount}; output={liveResult.SclPath}");
SetStatus($"{device.Name}: legacy SAS CID exported with one RCB — {row.Name}.");
return new RcbExportCompletion
{
OutputPath = liveResult.SclPath,
ReportPath = liveResult.ReportPath,
SummaryPath = liveResult.SummaryPath,
SchemaDisplayName = liveResult.SclSchema,
RetainedReportControl = row.Reference,
DataSetName = row.DataSetName,
DataSetMemberCount = row.MemberCount,
RemovedReportControlCount = removedCount,
Message = $"Export complete: {row.Reference} is the only RCB in the generated CID."
};
}
private static string EffectiveSclIedName(Iec61850MonitorDevice device)
=> string.IsNullOrWhiteSpace(device.SclIedName) ? device.Name : device.SclIedName;
private static string LastReferenceSegment(string? reference)
{
var text = (reference ?? string.Empty).Trim().Replace('$', '.');
var index = text.LastIndexOf('.');
return index < 0 ? text : text[(index + 1)..];
}
private static string NormalizeRcbReference(string? reference)
=> (reference ?? string.Empty).Trim().Replace('$', '.').ToLowerInvariant();
}