-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathMainWindow.IoTesting.cs
More file actions
420 lines (387 loc) · 15.9 KB
/
Copy pathMainWindow.IoTesting.cs
File metadata and controls
420 lines (387 loc) · 15.9 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
using System.IO;
using System.Text.Json;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Media;
using System.Windows.Threading;
using ArIED61850Tester.Models;
using ArIED61850Tester.Models.IoTesting;
using ArIED61850Tester.Services.IoTesting;
using Microsoft.Win32;
namespace ArIED61850Tester;
public partial class MainWindow
{
private readonly IoListExcelImportService _ioListExcelImportService = new();
private readonly IoTestLiveBindingService _ioTestLiveBindingService = new();
private FrameworkElement? _ioListTestingLauncherCard;
private IoTestSessionController? _activeIoTestSessionController;
private long _ioTestObservationSequence;
protected override void OnInitialized(EventArgs e)
{
base.OnInitialized(e);
Dispatcher.BeginInvoke(new Action(InstallFirstRunTestingChoices), DispatcherPriority.Loaded);
}
private void InstallFirstRunTestingChoices()
{
if (_ioListTestingLauncherCard != null || MainTabs.Items.Count == 0)
return;
if (MainTabs.Items[0] is not TabItem explorerTab || explorerTab.Content is not Grid explorerGrid)
return;
var workspace = explorerGrid.Children
.OfType<Grid>()
.FirstOrDefault(child => Grid.GetColumn(child) == 2);
var emptyState = workspace?.Children
.OfType<Border>()
.FirstOrDefault(border =>
BindingOperations.GetBinding(border, UIElement.VisibilityProperty)?.Path?.Path == nameof(EmptyExplorerVisibility));
if (emptyState?.Child is not Grid heroGrid)
return;
var generalTestingCard = heroGrid.Children.OfType<Border>().SingleOrDefault();
if (generalTestingCard?.Child is not StackPanel generalContent)
return;
heroGrid.Children.Remove(generalTestingCard);
ConfigureGeneralTestingCard(generalTestingCard, generalContent);
var ioListCard = CreateIoListTestingCard();
var chooser = new WrapPanel
{
Orientation = Orientation.Horizontal,
HorizontalAlignment = HorizontalAlignment.Center,
VerticalAlignment = VerticalAlignment.Bottom,
Margin = new Thickness(28),
MaxWidth = 1000
};
chooser.Children.Add(generalTestingCard);
chooser.Children.Add(ioListCard);
heroGrid.Children.Add(chooser);
_ioListTestingLauncherCard = ioListCard;
}
private void ConfigureGeneralTestingCard(Border card, StackPanel content)
{
card.Width = 510;
card.MaxWidth = 510;
card.Margin = new Thickness(0, 0, 12, 0);
card.HorizontalAlignment = HorizontalAlignment.Stretch;
card.VerticalAlignment = VerticalAlignment.Stretch;
card.BorderBrush = BrushFromHex("#DCE6F5");
card.BorderThickness = new Thickness(1);
var title = content.Children.OfType<TextBlock>().FirstOrDefault();
var description = content.Children.OfType<TextBlock>().Skip(1).FirstOrDefault();
var actions = content.Children.OfType<WrapPanel>().FirstOrDefault();
if (title == null || description == null || actions == null)
return;
content.Children.Insert(0, new TextBlock
{
Text = "GENERAL IEC 61850 TESTING",
Style = TryFindResource("MicroLabel") as Style,
Foreground = TryFindResource("Accent") as Brush,
Margin = new Thickness(0, 0, 0, 6)
});
title.Text = "Add an IED for general testing";
description.Text = "Connect a relay by IP for model discovery, signal selection, live monitoring, event analysis, and the complete IEC 61850 engineering workflow.";
actions.Children.Clear();
actions.Children.Add(CreateLauncherButton(
"Add IED",
"LucidePlus",
"PrimaryButton",
AddRelay_Click,
Brushes.White,
new Thickness(0, 0, 10, 0)));
actions.Children.Add(CreateLauncherButton(
"Open Project",
"LucideFolderOpen",
"SoftButton",
OpenProject_Click,
null,
new Thickness(0, 0, 10, 0)));
actions.Children.Add(new TextBlock
{
Text = "Manual discovery and general-purpose testing",
Style = TryFindResource("Caption") as Style,
VerticalAlignment = VerticalAlignment.Center
});
}
private Border CreateIoListTestingCard()
{
var card = new Border
{
Width = 430,
MaxWidth = 430,
Background = BrushFromHex("#F8FAFC"),
Opacity = 0.94,
CornerRadius = new CornerRadius(22),
Padding = new Thickness(22),
BorderBrush = BrushFromHex("#BFD2F1"),
BorderThickness = new Thickness(1),
HorizontalAlignment = HorizontalAlignment.Stretch,
VerticalAlignment = VerticalAlignment.Stretch
};
var content = new StackPanel();
content.Children.Add(new TextBlock
{
Text = "FAT / IO LIST TESTING",
Style = TryFindResource("MicroLabel") as Style,
Foreground = TryFindResource("Accent") as Brush,
Margin = new Thickness(0, 0, 0, 6)
});
content.Children.Add(new TextBlock
{
Text = "Run or continue FAT from an IO List",
FontSize = 24,
FontWeight = FontWeights.SemiBold,
Foreground = TryFindResource("Ink") as Brush,
TextWrapping = TextWrapping.Wrap
});
content.Children.Add(new TextBlock
{
Text = "Import the ARSAS Excel template for a new project, or open a portable .arsas project to continue saved progress from another laptop.",
TextWrapping = TextWrapping.Wrap,
FontSize = 13.4,
Foreground = TryFindResource("Muted") as Brush,
Margin = new Thickness(0, 10, 0, 18)
});
content.Children.Add(CreateLauncherButton(
"Open IO List Workbook",
"LucideFileInput",
"PrimaryButton",
OpenIoListTesting_Click,
Brushes.White,
new Thickness(0, 0, 0, 8)));
content.Children.Add(CreateLauncherButton(
"Open ARSAS Project",
"LucideFolderOpen",
"SoftButton",
OpenIoListPackage_Click,
null,
new Thickness(0, 0, 0, 10)));
content.Children.Add(new TextBlock
{
Text = "Autosave · portable continuation · verified evidence · native PDF report",
Style = TryFindResource("Caption") as Style,
TextWrapping = TextWrapping.Wrap
});
card.Child = content;
return card;
}
private Button CreateLauncherButton(
string text,
string iconResource,
string styleResource,
RoutedEventHandler handler,
Brush? iconStroke,
Thickness margin)
{
var icon = new System.Windows.Shapes.Path
{
Data = TryFindResource(iconResource) as Geometry,
Style = TryFindResource("LucideIcon") as Style
};
if (iconStroke != null)
icon.Stroke = iconStroke;
var buttonContent = new StackPanel
{
Orientation = Orientation.Horizontal,
HorizontalAlignment = HorizontalAlignment.Center
};
buttonContent.Children.Add(new Viewbox
{
Width = 15,
Height = 15,
Margin = new Thickness(0, 0, 7, 0),
Child = icon
});
buttonContent.Children.Add(new TextBlock
{
Text = text,
FontWeight = FontWeights.SemiBold
});
var button = new Button
{
Style = TryFindResource(styleResource) as Style,
Content = buttonContent,
Padding = new Thickness(12, 8, 12, 8),
Margin = margin,
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Stretch
};
button.Click += handler;
return button;
}
private static Brush BrushFromHex(string value)
=> new SolidColorBrush((Color)ColorConverter.ConvertFromString(value));
private async void OpenIoListTesting_Click(object sender, RoutedEventArgs e)
{
var dialog = new OpenFileDialog
{
Title = "Import ARSAS IO List FAT workbook",
Filter = "ARSAS IO List workbook (*.xlsx)|*.xlsx|Excel workbook (*.xlsx)|*.xlsx",
CheckFileExists = true,
Multiselect = false
};
if (dialog.ShowDialog(this) != true)
return;
SetStatus($"Importing IO List test plan from {Path.GetFileName(dialog.FileName)}…");
try
{
var import = await _ioListExcelImportService.ImportAsync(
dialog.FileName,
_applicationCancellation.Token);
var errors = import.AllFindings
.Where(finding => finding.Severity == IoTestImportFindingSeverity.Error)
.ToList();
if (!import.IsValid)
{
var details = string.Join(
Environment.NewLine,
errors.Take(12).Select(finding => $"• {finding.Code}: {finding.Message}"));
if (errors.Count > 12)
details += $"{Environment.NewLine}• …and {errors.Count - 12} more error(s).";
SetStatus("IO List import was rejected. The source workbook was not guessed or partially executed.");
MessageBox.Show(
this,
$"ARSAS could not import this IO List workbook safely.\n\n{details}",
"IO List import rejected",
MessageBoxButton.OK,
MessageBoxImage.Warning);
return;
}
var launch = await IoTestWorkspaceBootstrapService.OpenWorkbookAsync(
import.Project,
dialog.FileName,
IoTestingProjectsRoot(),
IoTestingEvidenceRoot(),
CreateIoTestSession,
_applicationCancellation.Token);
var importWarnings = import.AllFindings.Count(finding => finding.Severity == IoTestImportFindingSeverity.Warning);
await ShowIoTestingWorkspaceAsync(launch, importWarnings);
}
catch (OperationCanceledException)
{
SetStatus("IO List import cancelled.");
}
catch (Exception ex) when (ex is IOException or JsonException or InvalidDataException or UnauthorizedAccessException or ArgumentException or InvalidOperationException)
{
ShowIoTestingFailure(ex, "IO List import failed");
}
}
private async void OpenIoListPackage_Click(object sender, RoutedEventArgs e)
{
var dialog = new OpenFileDialog
{
Title = "Open ARSAS IO FAT project",
Filter = IoFatProjectPackageService.OpenDialogFilter,
CheckFileExists = true,
Multiselect = false
};
if (dialog.ShowDialog(this) != true)
return;
SetStatus($"Opening ARSAS IO FAT project {Path.GetFileName(dialog.FileName)}…");
try
{
var launch = await IoTestWorkspaceBootstrapService.OpenPackageAsync(
dialog.FileName,
IoTestingProjectsRoot(),
IoTestingEvidenceRoot(),
CreateIoTestSession,
_applicationCancellation.Token);
await ShowIoTestingWorkspaceAsync(launch, 0);
}
catch (OperationCanceledException)
{
SetStatus("ARSAS IO FAT project import cancelled.");
}
catch (Exception ex) when (ex is IOException or JsonException or InvalidDataException or UnauthorizedAccessException or ArgumentException or InvalidOperationException)
{
ShowIoTestingFailure(ex, "ARSAS IO FAT project import failed");
}
}
private Task ShowIoTestingWorkspaceAsync(IoTestWorkspaceLaunchResult launch, int importWarningCount)
{
var binding = _ioTestLiveBindingService.Bind(launch.Project, Devices);
var restoredText = launch.RestoredProgress ? "saved progress restored" : "new project";
SetStatus(
$"IO List ready: {launch.Project.Ieds.Count} IED, {launch.Project.SignalCount} SDI, " +
$"{binding.SignalBoundCount} live-bound, {restoredText}, {importWarningCount + launch.Warnings.Count} warning(s).");
if (launch.Warnings.Count > 0)
{
MessageBox.Show(
this,
string.Join(Environment.NewLine, launch.Warnings.Take(12).Select(warning => $"• {warning}")),
"IO FAT workspace warnings",
MessageBoxButton.OK,
MessageBoxImage.Information);
}
using var controller = launch.Session;
using var persistence = launch.Workspace;
var window = new IoListTestingWindow(launch.Project, controller, persistence) { Owner = this };
_activeIoTestSessionController = controller;
Interlocked.Exchange(ref _ioTestObservationSequence, DateTime.UtcNow.Ticks);
_runtime.PointUpdated += Runtime_IoTestPointUpdated;
Hide();
try
{
window.ShowDialog();
}
finally
{
_runtime.PointUpdated -= Runtime_IoTestPointUpdated;
_activeIoTestSessionController = null;
Show();
if (WindowState == System.Windows.WindowState.Minimized)
WindowState = System.Windows.WindowState.Normal;
Activate();
}
return Task.CompletedTask;
}
private IoTestSessionController CreateIoTestSession(IoTestProject project, string evidenceRoot)
=> new(
project,
ResolveIoTestDevice,
action => Dispatcher.BeginInvoke(action, DispatcherPriority.Background),
evidenceRoot);
private static string IoTestingProjectsRoot() => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"ARSAS",
"IO Testing Projects");
private static string IoTestingEvidenceRoot() => Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
"ARSAS",
"IO Testing Evidence");
private void ShowIoTestingFailure(Exception ex, string title)
{
AddLog("ERROR", "IO Testing", ex.Message);
MarkDiagnosticAlert();
SetStatus($"{title}. Diagnostics is marked with !.");
MessageBox.Show(this, ex.Message, title, MessageBoxButton.OK, MessageBoxImage.Error);
}
private void Runtime_IoTestPointUpdated(Iec61850PointSnapshot snapshot)
{
var point = snapshot.Point;
_activeIoTestSessionController?.Enqueue(new Iec61850EventEntry
{
Sequence = Interlocked.Increment(ref _ioTestObservationSequence),
DeviceId = point.DeviceId,
PointKey = point.PointKey,
DeviceTimestamp = snapshot.DeviceTimestamp,
DeviceName = point.DeviceName,
IpAddress = point.IpAddress,
SignalName = point.SignalName,
IecReference = point.IecReference,
OldValue = snapshot.PreviousValue,
NewValue = snapshot.Value,
Quality = snapshot.Quality,
SourceMode = snapshot.SourceMode,
Reason = snapshot.Reason
});
}
private Iec61850MonitorDevice? ResolveIoTestDevice(string key)
{
if (string.IsNullOrWhiteSpace(key))
return null;
return Devices.FirstOrDefault(device =>
device.DeviceId.Equals(key, StringComparison.OrdinalIgnoreCase) ||
device.Name.Equals(key, StringComparison.OrdinalIgnoreCase) ||
device.SclIedName.Equals(key, StringComparison.OrdinalIgnoreCase) ||
device.IpAddress.Equals(key, StringComparison.OrdinalIgnoreCase));
}
}