Repository navigation
Expand file tree
/
Copy pathComtradeWorkspaceWindow.P1D4LiveScrub.cs
More file actions
395 lines (352 loc) · 14.8 KB
/
Copy pathComtradeWorkspaceWindow.P1D4LiveScrub.cs
File metadata and controls
395 lines (352 loc) · 14.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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
using System.Windows.Media;
using ArIED61850Tester.Services;
namespace ArIED61850Tester;
public partial class ComtradeWorkspaceWindow
{
private const int P1D4PhasorCacheCapacity = 64;
// P1D.4 field-scrub path. Visual cursor motion is synchronous and cheap; native analysis is
// coalesced at WPF composition cadence with at most one worker in flight. A final mouse-up
// revision invalidates any older in-flight result so the view cannot flash back to a stale
// phasor/harmonic frame after the user has already stopped scrubbing.
private bool _p1d4ScrubRenderingHooked;
private bool _p1d4ScrubWorkerRunning;
private bool _p1d4ScrubDirty;
private bool _p1d4FinalRequested;
private long _p1d4TargetRevision;
private long _p1d4SettledRevision;
private AnalysisMode? _p1d4OwnedAnalysisMode;
private CancellationTokenSource? _p1d4ScrubCts = new();
private IReadOnlyList<ComtradePhasorChannelDescriptor>? _p1d4VoltageChannels;
private IReadOnlyList<ComtradePhasorChannelDescriptor>? _p1d4CurrentChannels;
private readonly BoundedFifoCache<ulong, ComtradePhasorWorkspaceResult> _p1d4PhasorFrameCache =
new(P1D4PhasorCacheCapacity);
private void QueueP1D4LiveAnalysisScrub(bool isFinal)
{
if (_analysisMode == AnalysisMode.Waveform) return;
if (_p1d4OwnedAnalysisMode != _analysisMode)
{
StopAnalysisRenderingPump();
ResetAnalysisContext();
_p1d4OwnedAnalysisMode = _analysisMode;
}
unchecked { _p1d4TargetRevision++; }
if (_p1d4TargetRevision <= 0) _p1d4TargetRevision = 1;
_p1d4ScrubDirty = true;
if (isFinal)
{
_p1d4FinalRequested = true;
_p1d4SettledRevision = _p1d4TargetRevision;
}
if (!_p1d4ScrubWorkerRunning)
EnsureP1D4LiveAnalysisRenderingPump();
}
private void EnsureP1D4LiveAnalysisRenderingPump()
{
if (_p1d4ScrubRenderingHooked) return;
CompositionTarget.Rendering += P1D4LiveAnalysisCompositionFrame;
_p1d4ScrubRenderingHooked = true;
}
private void StopP1D4LiveAnalysisRenderingPump()
{
if (!_p1d4ScrubRenderingHooked) return;
CompositionTarget.Rendering -= P1D4LiveAnalysisCompositionFrame;
_p1d4ScrubRenderingHooked = false;
}
private void StopP1D4LiveAnalysisScrub()
{
StopP1D4LiveAnalysisRenderingPump();
_p1d4ScrubDirty = false;
_p1d4FinalRequested = false;
_p1d4OwnedAnalysisMode = null;
unchecked { _p1d4TargetRevision++; }
_p1d4SettledRevision = _p1d4TargetRevision;
_p1d4ScrubCts?.Cancel();
_p1d4ScrubCts?.Dispose();
_p1d4ScrubCts = null;
}
private void P1D4LiveAnalysisCompositionFrame(object? sender, EventArgs e)
{
if (_analysisMode == AnalysisMode.Waveform)
{
StopP1D4LiveAnalysisRenderingPump();
return;
}
if (_p1d4ScrubWorkerRunning || !_p1d4ScrubDirty)
return;
_p1d4ScrubDirty = false;
var final = _p1d4FinalRequested;
_p1d4FinalRequested = false;
if (!TryCreateP1D4LiveAnalysisRequest(final, out var request))
{
if (!_p1d4ScrubDirty)
StopP1D4LiveAnalysisRenderingPump();
return;
}
if (IsP1D4AnalysisAlreadyRendered(request))
{
if (!_p1d4ScrubDirty)
StopP1D4LiveAnalysisRenderingPump();
return;
}
_p1d4ScrubWorkerRunning = true;
StopP1D4LiveAnalysisRenderingPump();
_ = ExecuteP1D4LiveAnalysisRequestAsync(request);
}
private bool TryCreateP1D4LiveAnalysisRequest(bool isFinal, out P1D4LiveAnalysisRequest request)
{
request = default;
if (_record.Info.FrameCount == 0) return false;
if (_analysisMode == AnalysisMode.Phasor)
{
EnsurePhasorCursor();
var referenceMilliseconds = _phasorCursorMilliseconds ??
(DisturbanceView.ViewStartMilliseconds + DisturbanceView.ViewEndMilliseconds) * 0.5;
if (!TryResolveDisturbanceFrameAtMilliseconds(referenceMilliseconds, out var frame) &&
!TryResolveDisturbanceViewportCenterFrame(out frame))
return false;
request = new P1D4LiveAnalysisRequest(
AnalysisMode.Phasor,
frame,
null,
string.Empty,
referenceMilliseconds,
_p1d4TargetRevision,
isFinal);
return true;
}
var harmonicSignals = ResolveP1D4HarmonicOverviewSignals();
if (harmonicSignals.Count == 0) return false;
EnsureHarmonicCursor();
var harmonicMilliseconds = _harmonicCursorMilliseconds ??
(DisturbanceView.ViewStartMilliseconds + DisturbanceView.ViewEndMilliseconds) * 0.5;
if (!TryResolveDisturbanceFrameAtMilliseconds(harmonicMilliseconds, out var harmonicFrame) &&
!TryResolveDisturbanceViewportCenterFrame(out harmonicFrame))
return false;
request = new P1D4LiveAnalysisRequest(
AnalysisMode.Harmonics,
harmonicFrame,
harmonicSignals,
BuildP1D4HarmonicOverviewSignature(harmonicSignals),
harmonicMilliseconds,
_p1d4TargetRevision,
isFinal);
return true;
}
private bool IsP1D4AnalysisAlreadyRendered(P1D4LiveAnalysisRequest request)
=> request.Mode == AnalysisMode.Phasor
? request.ReferenceFrame == _lastRenderedPhasorFrame
: request.ReferenceFrame == _p1d4LastRenderedHarmonicOverviewFrame &&
string.Equals(
request.HarmonicSignature,
_p1d4LastRenderedHarmonicOverviewSignature,
StringComparison.Ordinal);
private async Task ExecuteP1D4LiveAnalysisRequestAsync(P1D4LiveAnalysisRequest request)
{
try
{
var outcome = await TryLoadP1D4LiveAnalysisAsync(request, EnsureP1D4ScrubToken()).ConfigureAwait(true);
if (outcome.State == P1D4LiveAnalysisState.Cancelled || !ShouldPresentP1D4LiveAnalysis(request))
return;
if (outcome.State == P1D4LiveAnalysisState.Failed)
{
StatusTextBlock.Text = outcome.OperatorMessage;
return;
}
if (request.Mode == AnalysisMode.Phasor && outcome.Phasor is { } phasor)
{
PresentPhasor(request.ReferenceFrame, request.ReferenceMilliseconds, phasor);
return;
}
if (request.Mode == AnalysisMode.Harmonics && outcome.Harmonics is { Count: > 0 } overview)
{
PresentP1D4HarmonicOverview(
request.ReferenceFrame,
request.ReferenceMilliseconds,
request.HarmonicSignature,
overview);
}
}
finally
{
_p1d4ScrubWorkerRunning = false;
if (_p1d4ScrubDirty && _analysisMode != AnalysisMode.Waveform)
EnsureP1D4LiveAnalysisRenderingPump();
else
StopP1D4LiveAnalysisRenderingPump();
}
}
/// <summary>
/// Native/framework exceptions are contained at this asynchronous boundary and translated into
/// an explicit result state. Expected cancellation never reaches presentation as an error.
/// Detailed exception context is handed to the bounded diagnostic queue without blocking UI.
/// </summary>
private async Task<P1D4LiveAnalysisOutcome> TryLoadP1D4LiveAnalysisAsync(
P1D4LiveAnalysisRequest request,
CancellationToken token)
{
try
{
if (token.IsCancellationRequested)
return P1D4LiveAnalysisOutcome.Cancelled();
if (request.Mode == AnalysisMode.Phasor)
{
if (!_p1d4PhasorFrameCache.TryGetValue(request.ReferenceFrame, out var phasor))
{
phasor = await LoadP1D4PhasorWorkspaceAsync(request.ReferenceFrame, token).ConfigureAwait(true);
if (token.IsCancellationRequested)
return P1D4LiveAnalysisOutcome.Cancelled();
_p1d4PhasorFrameCache.Set(request.ReferenceFrame, phasor);
}
return P1D4LiveAnalysisOutcome.Success(phasor);
}
if (request.HarmonicSignals is not { Count: > 0 } harmonicSignals)
{
return P1D4LiveAnalysisOutcome.Failed(
"HARMONIC_SELECTION_EMPTY",
"Native COMTRADE harmonics unavailable: no checked analog channel is active.");
}
var overview = await LoadP1D4HarmonicOverviewAsync(
harmonicSignals,
request.ReferenceFrame,
token).ConfigureAwait(true);
if (token.IsCancellationRequested)
return P1D4LiveAnalysisOutcome.Cancelled();
return P1D4LiveAnalysisOutcome.Success(overview);
}
catch (OperationCanceledException)
{
return P1D4LiveAnalysisOutcome.Cancelled();
}
catch (ObjectDisposedException)
{
return P1D4LiveAnalysisOutcome.Cancelled();
}
catch (Exception ex)
{
var code = request.Mode == AnalysisMode.Phasor
? "PHASOR_NATIVE_FAILURE"
: "HARMONIC_NATIVE_FAILURE";
ComtradeDiagnosticQueue.TryEnqueue(
"P1D4.LiveAnalysis",
code,
$"Mode={request.Mode}; frame={request.ReferenceFrame}; revision={request.Revision}; final={request.IsFinal}",
ex);
return P1D4LiveAnalysisOutcome.Failed(
code,
$"Native COMTRADE {request.Mode.ToString().ToLowerInvariant()} analysis is unavailable at this reference. Diagnostics captured.");
}
}
private bool ShouldPresentP1D4LiveAnalysis(P1D4LiveAnalysisRequest request)
{
if (request.Mode != _analysisMode)
return false;
if (request.Mode == AnalysisMode.Harmonics)
{
var currentSignals = ResolveP1D4HarmonicOverviewSignals();
if (!string.Equals(
request.HarmonicSignature,
BuildP1D4HarmonicOverviewSignature(currentSignals),
StringComparison.Ordinal))
return false;
}
return request.Revision >= _p1d4SettledRevision;
}
private CancellationToken EnsureP1D4ScrubToken()
{
if (_p1d4ScrubCts is null || _p1d4ScrubCts.IsCancellationRequested)
{
_p1d4ScrubCts?.Dispose();
_p1d4ScrubCts = new CancellationTokenSource();
}
return _p1d4ScrubCts.Token;
}
private async Task<ComtradePhasorWorkspaceResult> LoadP1D4PhasorWorkspaceAsync(
ulong referenceFrame,
CancellationToken token)
{
await _nativeGate.WaitAsync(token).ConfigureAwait(false);
try
{
return await Task.Run(() =>
{
token.ThrowIfCancellationRequested();
EnsureP1D4PhasorChannelSets(token);
return new ComtradePhasorWorkspaceResult(
ReadPhasorVectors(_p1d4VoltageChannels!, referenceFrame, token),
ReadPhasorVectors(_p1d4CurrentChannels!, referenceFrame, token));
}, token).ConfigureAwait(false);
}
finally
{
_nativeGate.Release();
}
}
private void EnsureP1D4PhasorChannelSets(CancellationToken token)
{
if (_p1d4VoltageChannels is not null && _p1d4CurrentChannels is not null)
return;
var descriptors = new List<ComtradePhasorChannelDescriptor>(_record.AnalogChannels.Count);
for (var index = 0; index < _record.AnalogChannels.Count; index++)
{
token.ThrowIfCancellationRequested();
var channel = _record.AnalogChannels[index];
var hasSemantics = _record.TryReadAnalogSemantics(checked((uint)index), out var semantics) && semantics is not null;
var fallbackPhase = NormalizePhase(channel.Phase, channel.Id);
var role = hasSemantics
? semantics!.Role
: ResolveAnalogSection(channel.Units, null) switch
{
"Voltage" => ComtradePhasorWorkspaceMath.RoleVoltage,
"Current" => ComtradePhasorWorkspaceMath.RoleCurrent,
_ => 0
};
var phaseRole = hasSemantics
? semantics!.PhaseRole
: ComtradePhasorWorkspaceMath.PhaseRoleFromCanonicalName(fallbackPhase);
descriptors.Add(new ComtradePhasorChannelDescriptor(
checked((uint)index),
role,
phaseRole,
channel.Id,
ComtradePhasorWorkspaceMath.CanonicalPhaseName(phaseRole, fallbackPhase),
channel.Circuit,
channel.Units));
}
_p1d4VoltageChannels = ComtradePhasorWorkspaceMath
.SelectRoleSet(descriptors, ComtradePhasorWorkspaceMath.RoleVoltage)
.ToArray();
_p1d4CurrentChannels = ComtradePhasorWorkspaceMath
.SelectRoleSet(descriptors, ComtradePhasorWorkspaceMath.RoleCurrent)
.ToArray();
}
private enum P1D4LiveAnalysisState
{
Success,
Cancelled,
Failed
}
private readonly record struct P1D4LiveAnalysisOutcome(
P1D4LiveAnalysisState State,
ComtradePhasorWorkspaceResult? Phasor,
IReadOnlyList<P1D4HarmonicOverviewEntry>? Harmonics,
string ErrorCode,
string OperatorMessage)
{
internal static P1D4LiveAnalysisOutcome Success(ComtradePhasorWorkspaceResult phasor)
=> new(P1D4LiveAnalysisState.Success, phasor, null, string.Empty, string.Empty);
internal static P1D4LiveAnalysisOutcome Success(IReadOnlyList<P1D4HarmonicOverviewEntry> harmonics)
=> new(P1D4LiveAnalysisState.Success, null, harmonics, string.Empty, string.Empty);
internal static P1D4LiveAnalysisOutcome Cancelled()
=> new(P1D4LiveAnalysisState.Cancelled, null, null, "CANCELLED", string.Empty);
internal static P1D4LiveAnalysisOutcome Failed(string code, string operatorMessage)
=> new(P1D4LiveAnalysisState.Failed, null, null, code, operatorMessage);
}
private readonly record struct P1D4LiveAnalysisRequest(
AnalysisMode Mode,
ulong ReferenceFrame,
IReadOnlyList<ComtradeSignalItem>? HarmonicSignals,
string HarmonicSignature,
double ReferenceMilliseconds,
long Revision,
bool IsFinal);
}