730 lines
27 KiB
C#
730 lines
27 KiB
C#
using System.Globalization;
|
|
using System.Runtime.CompilerServices;
|
|
using System.Text.Json;
|
|
using AutoForge.Application.Features.Vehicles.Diagnostics;
|
|
using AutoForge.Diagnostics;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
using Microsoft.Extensions.DependencyInjection.Extensions;
|
|
|
|
namespace AutoForge.Application.Features.Vehicles.Telemetry.LiveDashboard;
|
|
|
|
public interface ILiveDashboardPollScheduler
|
|
{
|
|
Task WaitAsync(TimeSpan interval, CancellationToken cancellationToken);
|
|
}
|
|
|
|
public sealed class SystemLiveDashboardPollScheduler : ILiveDashboardPollScheduler
|
|
{
|
|
public Task WaitAsync(TimeSpan interval, CancellationToken cancellationToken) =>
|
|
Task.Delay(interval, cancellationToken);
|
|
}
|
|
|
|
public interface ILiveDashboardFeedFactory
|
|
{
|
|
LiveDashboardFeed Create(DiagnosticSession session);
|
|
}
|
|
|
|
public sealed class LiveDashboardFeedFactory(ILiveDashboardPollScheduler scheduler)
|
|
: ILiveDashboardFeedFactory
|
|
{
|
|
private readonly object _gate = new();
|
|
private readonly ConditionalWeakTable<DiagnosticSession, LiveDashboardFeed> _feeds = new();
|
|
|
|
public LiveDashboardFeed Create(DiagnosticSession session)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(session);
|
|
lock (_gate)
|
|
{
|
|
ObjectDisposedException.ThrowIf(session.IsClosed, session);
|
|
return _feeds.GetValue(session, source => new LiveDashboardFeed(source, scheduler));
|
|
}
|
|
}
|
|
}
|
|
|
|
public sealed class LiveDashboardFeed : IAsyncDisposable
|
|
{
|
|
public static readonly TimeSpan PollInterval = TimeSpan.FromMilliseconds(250);
|
|
|
|
private readonly DiagnosticSession _session;
|
|
private readonly ILiveDashboardPollScheduler _scheduler;
|
|
private readonly object _gate = new();
|
|
private readonly Dictionary<string, DiagnosticEndpoint> _eligibleEndpoints =
|
|
new(StringComparer.OrdinalIgnoreCase);
|
|
private readonly Dictionary<string, Dictionary<string, DiagnosticSignal>> _lastSignals =
|
|
new(StringComparer.OrdinalIgnoreCase);
|
|
private readonly Dictionary<string, DashboardModuleStatus> _moduleStatuses =
|
|
new(StringComparer.OrdinalIgnoreCase);
|
|
private readonly Dictionary<(string Module, string Signal), DashboardSignalBinding> _knownBindings =
|
|
new(new SignalKeyComparer());
|
|
private readonly Dictionary<(string Module, string Signal), DiagnosticSignal> _lastFiniteSignals =
|
|
new(new SignalKeyComparer());
|
|
private IReadOnlyList<DashboardGaugeDefinition> _definitions = [];
|
|
private DashboardFeedState _state = DashboardFeedState.Stopped;
|
|
private LiveDashboardSnapshot _snapshot;
|
|
private CancellationTokenSource? _ownerCancellation;
|
|
private Task? _ownerTask;
|
|
private Task? _initializationTask;
|
|
private Task? _stopTask;
|
|
private long _cycle;
|
|
private string? _error;
|
|
private bool _disposed;
|
|
private Task? _disposeTask;
|
|
|
|
internal LiveDashboardFeed(
|
|
DiagnosticSession session,
|
|
ILiveDashboardPollScheduler scheduler)
|
|
{
|
|
_session = session ?? throw new ArgumentNullException(nameof(session));
|
|
_scheduler = scheduler ?? throw new ArgumentNullException(nameof(scheduler));
|
|
_snapshot = CreateSnapshotLocked();
|
|
_session.RegisterLifetimeResource(this);
|
|
}
|
|
|
|
public event Action? Changed;
|
|
|
|
public LiveDashboardSnapshot Snapshot
|
|
{
|
|
get
|
|
{
|
|
lock (_gate)
|
|
{
|
|
return _snapshot;
|
|
}
|
|
}
|
|
}
|
|
|
|
public void ReplaceDefinitions(IEnumerable<DashboardGaugeDefinition> definitions)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(definitions);
|
|
var proposed = definitions.ToArray();
|
|
lock (_gate)
|
|
{
|
|
EnsureNotDisposed();
|
|
ValidateDefinitions(proposed);
|
|
_definitions = Array.AsReadOnly(proposed.ToArray());
|
|
_snapshot = CreateSnapshotLocked();
|
|
}
|
|
|
|
Changed?.Invoke();
|
|
}
|
|
|
|
public async Task StartAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
Task initialization;
|
|
var changed = false;
|
|
lock (_gate)
|
|
{
|
|
EnsureNotDisposed();
|
|
if (_state == DashboardFeedState.Running)
|
|
{
|
|
return;
|
|
}
|
|
|
|
if (_state == DashboardFeedState.Starting && _initializationTask is not null)
|
|
{
|
|
initialization = _initializationTask;
|
|
}
|
|
else
|
|
{
|
|
if (_state == DashboardFeedState.Stopping ||
|
|
_ownerTask is { IsCompleted: false })
|
|
{
|
|
throw new InvalidOperationException(
|
|
"The previous dashboard acquisition owner is still stopping; retry after cleanup completes.");
|
|
}
|
|
|
|
_ownerCancellation?.Dispose();
|
|
_ownerCancellation = new CancellationTokenSource();
|
|
var initializationSource = new TaskCompletionSource(
|
|
TaskCreationOptions.RunContinuationsAsynchronously);
|
|
initialization = initializationSource.Task;
|
|
_initializationTask = initialization;
|
|
_stopTask = null;
|
|
_error = null;
|
|
_state = DashboardFeedState.Starting;
|
|
_snapshot = CreateSnapshotLocked();
|
|
_ownerTask = Task.Run(() => RunOwnerAsync(_ownerCancellation, initializationSource));
|
|
changed = true;
|
|
}
|
|
}
|
|
|
|
if (changed)
|
|
{
|
|
Changed?.Invoke();
|
|
}
|
|
|
|
await initialization.WaitAsync(cancellationToken).ConfigureAwait(false);
|
|
}
|
|
|
|
public Task StopAsync()
|
|
{
|
|
Task stop;
|
|
var changed = false;
|
|
lock (_gate)
|
|
{
|
|
EnsureNotDisposed();
|
|
if (_state == DashboardFeedState.Stopping && _stopTask is not null)
|
|
{
|
|
return _stopTask;
|
|
}
|
|
|
|
if (_ownerTask is not { } owner)
|
|
{
|
|
_state = DashboardFeedState.Stopped;
|
|
_initializationTask = null;
|
|
_snapshot = CreateSnapshotLocked();
|
|
stop = Task.CompletedTask;
|
|
changed = true;
|
|
}
|
|
else
|
|
{
|
|
_state = DashboardFeedState.Stopping;
|
|
_snapshot = CreateSnapshotLocked();
|
|
_ownerCancellation!.Cancel();
|
|
stop = StopOwnerAsync(owner, _ownerCancellation);
|
|
_stopTask = stop;
|
|
changed = true;
|
|
}
|
|
}
|
|
|
|
if (changed)
|
|
{
|
|
Changed?.Invoke();
|
|
}
|
|
|
|
return stop;
|
|
}
|
|
|
|
public ValueTask DisposeAsync()
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (_disposeTask is not null)
|
|
{
|
|
return new ValueTask(_disposeTask);
|
|
}
|
|
|
|
_disposeTask = DisposeCoreAsync();
|
|
return new ValueTask(_disposeTask);
|
|
}
|
|
}
|
|
|
|
private async Task DisposeCoreAsync()
|
|
{
|
|
try
|
|
{
|
|
await StopAsync().ConfigureAwait(false);
|
|
}
|
|
finally
|
|
{
|
|
lock (_gate)
|
|
{
|
|
_disposed = true;
|
|
_ownerCancellation?.Dispose();
|
|
_ownerCancellation = null;
|
|
_initializationTask = null;
|
|
Changed = null;
|
|
}
|
|
}
|
|
}
|
|
|
|
private async Task RunOwnerAsync(
|
|
CancellationTokenSource cancellation,
|
|
TaskCompletionSource initialization)
|
|
{
|
|
try
|
|
{
|
|
var token = cancellation.Token;
|
|
var discovery = await _session.DiscoverAsync(token).ConfigureAwait(false);
|
|
token.ThrowIfCancellationRequested();
|
|
var endpoints = discovery.Endpoints
|
|
.Where(entry =>
|
|
entry.Identity is not null &&
|
|
entry.ImplementedServices.Contains(DiagnosticServices.ReadSignals, StringComparer.Ordinal))
|
|
.Select(entry => entry.Endpoint)
|
|
.ToArray();
|
|
if (endpoints.Length == 0)
|
|
{
|
|
throw new InvalidOperationException(
|
|
"No identity-verified endpoint in this session advertises read.signals; monitoring cannot start.");
|
|
}
|
|
|
|
lock (_gate)
|
|
{
|
|
if (ReferenceEquals(_ownerCancellation, cancellation))
|
|
{
|
|
_eligibleEndpoints.Clear();
|
|
foreach (var endpoint in endpoints)
|
|
{
|
|
_eligibleEndpoints.Add(endpoint.ModuleIdentifier, endpoint);
|
|
}
|
|
}
|
|
}
|
|
|
|
await AcquireCycleAsync(token).ConfigureAwait(false);
|
|
token.ThrowIfCancellationRequested();
|
|
lock (_gate)
|
|
{
|
|
if (ReferenceEquals(_ownerCancellation, cancellation) && !token.IsCancellationRequested)
|
|
{
|
|
_state = DashboardFeedState.Running;
|
|
_snapshot = CreateSnapshotLocked();
|
|
}
|
|
}
|
|
|
|
token.ThrowIfCancellationRequested();
|
|
initialization.TrySetResult();
|
|
Changed?.Invoke();
|
|
|
|
while (true)
|
|
{
|
|
await _scheduler.WaitAsync(PollInterval, token).ConfigureAwait(false);
|
|
token.ThrowIfCancellationRequested();
|
|
await AcquireCycleAsync(token).ConfigureAwait(false);
|
|
token.ThrowIfCancellationRequested();
|
|
Changed?.Invoke();
|
|
}
|
|
}
|
|
catch (OperationCanceledException) when (cancellation.IsCancellationRequested)
|
|
{
|
|
initialization.TrySetCanceled(cancellation.Token);
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (ReferenceEquals(_ownerCancellation, cancellation))
|
|
{
|
|
_error = exception.Message;
|
|
_state = DashboardFeedState.Error;
|
|
_snapshot = CreateSnapshotLocked();
|
|
}
|
|
}
|
|
|
|
initialization.TrySetException(exception);
|
|
Changed?.Invoke();
|
|
}
|
|
}
|
|
|
|
private async Task AcquireCycleAsync(CancellationToken cancellationToken)
|
|
{
|
|
KeyValuePair<string, DiagnosticEndpoint>[] endpoints;
|
|
lock (_gate)
|
|
{
|
|
endpoints = _eligibleEndpoints.ToArray();
|
|
}
|
|
|
|
foreach (var (moduleIdentifier, endpoint) in endpoints)
|
|
{
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
var result = await _session.ReadSignalsAsync(endpoint, cancellationToken).ConfigureAwait(false);
|
|
cancellationToken.ThrowIfCancellationRequested();
|
|
if (result.IsSuccess)
|
|
{
|
|
var snapshot = result.Value!;
|
|
try
|
|
{
|
|
ValidateSnapshot(moduleIdentifier, snapshot);
|
|
lock (_gate)
|
|
{
|
|
var signals = snapshot.Signals.ToDictionary(
|
|
signal => signal.SignalIdentifier,
|
|
signal => signal,
|
|
StringComparer.Ordinal);
|
|
var bindings = new List<DashboardSignalBinding>(snapshot.Signals.Count);
|
|
foreach (var signal in snapshot.Signals)
|
|
{
|
|
var key = (moduleIdentifier, signal.SignalIdentifier);
|
|
var binding = new DashboardSignalBinding(
|
|
signal.ModuleIdentifier,
|
|
signal.SignalIdentifier,
|
|
signal.Unit,
|
|
signal.Origin);
|
|
if (_knownBindings.TryGetValue(key, out var previous) &&
|
|
(!StringComparer.Ordinal.Equals(previous.Unit, binding.Unit) ||
|
|
!StringComparer.Ordinal.Equals(previous.Origin, binding.Origin)))
|
|
{
|
|
throw new InvalidOperationException(
|
|
$"Signal '{signal.SignalIdentifier}' on '{moduleIdentifier}' changed its verified unit or origin.");
|
|
}
|
|
|
|
bindings.Add(binding);
|
|
}
|
|
|
|
_lastSignals[moduleIdentifier] = signals;
|
|
foreach (var signal in bindings)
|
|
{
|
|
var key = (moduleIdentifier, signal.SignalIdentifier);
|
|
_knownBindings.TryAdd(key, signal);
|
|
}
|
|
foreach (var signal in snapshot.Signals)
|
|
{
|
|
if (signal.Quality == SignalQuality.Good && TryGetFiniteNumber(signal, out _))
|
|
{
|
|
_lastFiniteSignals[(moduleIdentifier, signal.SignalIdentifier)] = signal;
|
|
}
|
|
}
|
|
|
|
_moduleStatuses[moduleIdentifier] =
|
|
new DashboardModuleStatus(moduleIdentifier, result.Outcome, null);
|
|
}
|
|
}
|
|
catch (InvalidOperationException exception)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
_moduleStatuses[moduleIdentifier] =
|
|
new DashboardModuleStatus(moduleIdentifier, DiagnosticOutcome.ProtocolError, exception.Message);
|
|
}
|
|
}
|
|
}
|
|
else
|
|
{
|
|
lock (_gate)
|
|
{
|
|
_moduleStatuses[moduleIdentifier] =
|
|
new DashboardModuleStatus(moduleIdentifier, result.Outcome, result.Error);
|
|
}
|
|
}
|
|
}
|
|
|
|
lock (_gate)
|
|
{
|
|
_cycle++;
|
|
_snapshot = CreateSnapshotLocked();
|
|
}
|
|
}
|
|
|
|
private void ValidateSnapshot(string requestedModule, SignalSnapshot snapshot)
|
|
{
|
|
if (!StringComparer.OrdinalIgnoreCase.Equals(snapshot.ModuleIdentifier, requestedModule))
|
|
{
|
|
throw new InvalidOperationException(
|
|
$"Signal response module '{snapshot.ModuleIdentifier}' did not match requested module '{requestedModule}'.");
|
|
}
|
|
|
|
foreach (var signal in snapshot.Signals)
|
|
{
|
|
if (!StringComparer.OrdinalIgnoreCase.Equals(signal.ModuleIdentifier, requestedModule))
|
|
{
|
|
throw new InvalidOperationException(
|
|
$"Signal '{signal.SignalIdentifier}' reported source module '{signal.ModuleIdentifier}' instead of '{requestedModule}'.");
|
|
}
|
|
|
|
var identity = _session.Identity;
|
|
if (!StringComparer.Ordinal.Equals(
|
|
signal.ModelConfigurationIdentifier,
|
|
identity.DynamicsConfigurationIdentifier) ||
|
|
!StringComparer.Ordinal.Equals(signal.ModelRunIdentifier, identity.DynamicsRunIdentifier))
|
|
{
|
|
throw new InvalidOperationException(
|
|
$"Signal '{signal.SignalIdentifier}' does not match the selected dynamics configuration/run context.");
|
|
}
|
|
}
|
|
}
|
|
|
|
private void ValidateDefinitions(IReadOnlyList<DashboardGaugeDefinition> definitions)
|
|
{
|
|
if (definitions.Count > 8)
|
|
{
|
|
throw new DashboardConfigurationException("A live dashboard supports no more than eight gauges.");
|
|
}
|
|
|
|
var identifiers = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
|
|
foreach (var definition in definitions)
|
|
{
|
|
if (definition is null)
|
|
{
|
|
throw new DashboardConfigurationException("Dashboard gauge definitions cannot contain null.");
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(definition.GaugeIdentifier) ||
|
|
!StringComparer.Ordinal.Equals(definition.GaugeIdentifier, definition.GaugeIdentifier.Trim()) ||
|
|
!identifiers.Add(definition.GaugeIdentifier))
|
|
{
|
|
throw new DashboardConfigurationException(
|
|
"Gauge identifiers must be nonblank, trimmed and unique ignoring case.");
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(definition.Label) ||
|
|
!StringComparer.Ordinal.Equals(definition.Label, definition.Label.Trim()))
|
|
{
|
|
throw new DashboardConfigurationException("Gauge labels must be nonblank and contain no surrounding whitespace.");
|
|
}
|
|
|
|
if (!Enum.IsDefined(definition.Kind))
|
|
{
|
|
throw new DashboardConfigurationException("The selected gauge kind is undefined.");
|
|
}
|
|
|
|
if (string.IsNullOrWhiteSpace(definition.ModuleIdentifier) ||
|
|
string.IsNullOrWhiteSpace(definition.SignalIdentifier) ||
|
|
string.IsNullOrWhiteSpace(definition.Unit))
|
|
{
|
|
throw new DashboardConfigurationException("Gauge module, signal and unit bindings must be explicit.");
|
|
}
|
|
|
|
if (!double.IsFinite(definition.Minimum) ||
|
|
!double.IsFinite(definition.Maximum) ||
|
|
!double.IsFinite(definition.Maximum - definition.Minimum) ||
|
|
definition.Maximum <= definition.Minimum)
|
|
{
|
|
throw new DashboardConfigurationException(
|
|
"Gauge range must have finite minimum, maximum and positive finite span.");
|
|
}
|
|
|
|
if (definition.DecimalPrecision is < 0 or > 3)
|
|
{
|
|
throw new DashboardConfigurationException("Gauge decimal precision must be an integer from 0 through 3.");
|
|
}
|
|
|
|
if (!_knownBindings.TryGetValue(
|
|
(definition.ModuleIdentifier, definition.SignalIdentifier),
|
|
out var binding))
|
|
{
|
|
throw new DashboardConfigurationException(
|
|
$"Signal '{definition.SignalIdentifier}' on module '{definition.ModuleIdentifier}' has not been read from an identity-verified endpoint in this session.");
|
|
}
|
|
|
|
if (!StringComparer.Ordinal.Equals(definition.Unit, binding.Unit))
|
|
{
|
|
throw new DashboardConfigurationException(
|
|
$"Gauge unit '{definition.Unit}' does not exactly match source unit '{binding.Unit}'; unit conversion is not supported.");
|
|
}
|
|
}
|
|
}
|
|
|
|
private LiveDashboardSnapshot CreateSnapshotLocked()
|
|
{
|
|
var available = Array.AsReadOnly(_knownBindings.Values
|
|
.OrderBy(item => item.ModuleIdentifier, StringComparer.OrdinalIgnoreCase)
|
|
.ThenBy(item => item.SignalIdentifier, StringComparer.Ordinal)
|
|
.ToArray());
|
|
var values = Array.AsReadOnly(_definitions.Select(CreateGaugeValueLocked).ToArray());
|
|
var modules = Array.AsReadOnly(_moduleStatuses.Values
|
|
.OrderBy(item => item.ModuleIdentifier, StringComparer.OrdinalIgnoreCase)
|
|
.ToArray());
|
|
return new LiveDashboardSnapshot(
|
|
_session.Identity,
|
|
_state,
|
|
available,
|
|
Array.AsReadOnly(_definitions.ToArray()),
|
|
values,
|
|
modules,
|
|
_cycle,
|
|
_error);
|
|
}
|
|
|
|
private DashboardGaugeValue CreateGaugeValueLocked(DashboardGaugeDefinition definition)
|
|
{
|
|
if (_state is DashboardFeedState.Stopped or DashboardFeedState.Stopping)
|
|
{
|
|
if (_lastFiniteSignals.TryGetValue(
|
|
(definition.ModuleIdentifier, definition.SignalIdentifier),
|
|
out var stoppedSignal) &&
|
|
TryGetFiniteNumber(stoppedSignal, out var stoppedNumber))
|
|
{
|
|
var stoppedState = GetRangeState(stoppedNumber, definition);
|
|
return CreateValue(definition, DashboardReadingState.Stopped, stoppedNumber, stoppedSignal,
|
|
$"Monitoring stopped; last source sample was at logical tick {stoppedSignal.LogicalTimeTicks}.",
|
|
stoppedState);
|
|
}
|
|
|
|
return new DashboardGaugeValue(
|
|
definition, DashboardReadingState.Stopped, "--", null, null,
|
|
"Monitoring stopped; no numeric source sample is available.", null);
|
|
}
|
|
|
|
if (_state == DashboardFeedState.Starting)
|
|
{
|
|
return new DashboardGaugeValue(
|
|
definition, DashboardReadingState.Pending, "--", null, null,
|
|
"Waiting for the first verified source sample.", null);
|
|
}
|
|
|
|
if (_state == DashboardFeedState.Error)
|
|
{
|
|
return LastOrError(definition, _error ?? "Dashboard acquisition stopped after an unexpected source error.");
|
|
}
|
|
|
|
DiagnosticSignal? signal = null;
|
|
_lastSignals.TryGetValue(definition.ModuleIdentifier, out var moduleSignals);
|
|
moduleSignals?.TryGetValue(definition.SignalIdentifier, out signal);
|
|
if (_moduleStatuses.TryGetValue(definition.ModuleIdentifier, out var moduleStatus) &&
|
|
moduleStatus.Outcome != DiagnosticOutcome.PositiveResponse)
|
|
{
|
|
return LastOrError(definition, moduleStatus.Error ?? $"Source read outcome: {moduleStatus.Outcome}.");
|
|
}
|
|
|
|
if (signal is null)
|
|
{
|
|
return LastOrError(
|
|
definition,
|
|
"The previously bound signal is missing from the latest source response.",
|
|
DashboardReadingState.Unavailable);
|
|
}
|
|
|
|
if (signal.Quality == SignalQuality.Unknown || !TryGetFiniteNumber(signal, out var value))
|
|
{
|
|
return new DashboardGaugeValue(
|
|
definition,
|
|
DashboardReadingState.Unknown,
|
|
"--",
|
|
null,
|
|
null,
|
|
signal.Quality == SignalQuality.Unknown
|
|
? "The source quality is Unknown."
|
|
: "The source value is null, non-numeric or non-finite.",
|
|
signal);
|
|
}
|
|
|
|
if (signal.Quality == SignalQuality.Uncertain)
|
|
{
|
|
return CreateValue(
|
|
definition,
|
|
DashboardReadingState.Uncertain,
|
|
value,
|
|
signal,
|
|
"The source marked this finite value Uncertain.",
|
|
GetRangeState(value, definition));
|
|
}
|
|
|
|
if (signal.Quality != SignalQuality.Good)
|
|
{
|
|
return new DashboardGaugeValue(
|
|
definition, DashboardReadingState.Unknown, "--", null, null,
|
|
"The source quality is undefined.", signal);
|
|
}
|
|
|
|
_lastFiniteSignals[(definition.ModuleIdentifier, definition.SignalIdentifier)] = signal;
|
|
return CreateValue(definition, GetRangeState(value, definition), value, signal, null);
|
|
}
|
|
|
|
private DashboardGaugeValue LastOrError(
|
|
DashboardGaugeDefinition definition,
|
|
string error,
|
|
DashboardReadingState missingState = DashboardReadingState.Error)
|
|
{
|
|
if (_lastFiniteSignals.TryGetValue((definition.ModuleIdentifier, definition.SignalIdentifier), out var last) &&
|
|
TryGetFiniteNumber(last, out var lastValue))
|
|
{
|
|
var rangeState = GetRangeState(lastValue, definition);
|
|
return CreateValue(
|
|
definition,
|
|
DashboardReadingState.Stale,
|
|
lastValue,
|
|
last,
|
|
$"{error} Retaining last-known sample from logical tick {last.LogicalTimeTicks}.",
|
|
rangeState);
|
|
}
|
|
|
|
return new DashboardGaugeValue(
|
|
definition, missingState, "--", null, null, error, null);
|
|
}
|
|
|
|
private static DashboardGaugeValue CreateValue(
|
|
DashboardGaugeDefinition definition,
|
|
DashboardReadingState state,
|
|
double value,
|
|
DiagnosticSignal signal,
|
|
string? reason,
|
|
DashboardReadingState? rangeState = null)
|
|
{
|
|
var outOfRangeState = rangeState ?? (state is DashboardReadingState.OutOfRangeLow or DashboardReadingState.OutOfRangeHigh
|
|
? state
|
|
: null);
|
|
var displayState = state is DashboardReadingState.OutOfRangeLow or DashboardReadingState.OutOfRangeHigh
|
|
? DashboardReadingState.Good
|
|
: state;
|
|
var barPercent = Math.Clamp((value - definition.Minimum) / (definition.Maximum - definition.Minimum) * 100, 0, 100);
|
|
return new DashboardGaugeValue(
|
|
definition,
|
|
displayState,
|
|
value.ToString($"F{definition.DecimalPrecision}", CultureInfo.InvariantCulture),
|
|
value,
|
|
barPercent,
|
|
reason,
|
|
signal,
|
|
outOfRangeState);
|
|
}
|
|
|
|
private static DashboardReadingState GetRangeState(double value, DashboardGaugeDefinition definition) =>
|
|
value < definition.Minimum
|
|
? DashboardReadingState.OutOfRangeLow
|
|
: value > definition.Maximum
|
|
? DashboardReadingState.OutOfRangeHigh
|
|
: DashboardReadingState.Good;
|
|
|
|
private static bool TryGetFiniteNumber(DiagnosticSignal signal, out double value)
|
|
{
|
|
value = default;
|
|
return signal.Value.ValueKind == JsonValueKind.Number &&
|
|
signal.Value.TryGetDouble(out value) &&
|
|
double.IsFinite(value);
|
|
}
|
|
|
|
private void EnsureNotDisposed()
|
|
{
|
|
ObjectDisposedException.ThrowIf(_disposed, this);
|
|
}
|
|
|
|
private async Task StopOwnerAsync(Task owner, CancellationTokenSource cancellation)
|
|
{
|
|
try
|
|
{
|
|
await owner.ConfigureAwait(false);
|
|
}
|
|
catch (Exception exception)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (ReferenceEquals(_ownerCancellation, cancellation))
|
|
{
|
|
_error ??= exception.Message;
|
|
}
|
|
}
|
|
}
|
|
finally
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (ReferenceEquals(_ownerCancellation, cancellation))
|
|
{
|
|
_ownerTask = null;
|
|
_ownerCancellation = null;
|
|
_initializationTask = null;
|
|
_stopTask = null;
|
|
_state = DashboardFeedState.Stopped;
|
|
_snapshot = CreateSnapshotLocked();
|
|
cancellation.Dispose();
|
|
}
|
|
}
|
|
|
|
Changed?.Invoke();
|
|
}
|
|
}
|
|
|
|
private sealed class SignalKeyComparer : IEqualityComparer<(string Module, string Signal)>
|
|
{
|
|
public bool Equals((string Module, string Signal) x, (string Module, string Signal) y) =>
|
|
StringComparer.OrdinalIgnoreCase.Equals(x.Module, y.Module) &&
|
|
StringComparer.Ordinal.Equals(x.Signal, y.Signal);
|
|
|
|
public int GetHashCode((string Module, string Signal) key) =>
|
|
HashCode.Combine(
|
|
StringComparer.OrdinalIgnoreCase.GetHashCode(key.Module),
|
|
StringComparer.Ordinal.GetHashCode(key.Signal));
|
|
}
|
|
}
|
|
|
|
public static class LiveDashboardServiceCollectionExtensions
|
|
{
|
|
public static IServiceCollection AddAutoForgeLiveDashboard(this IServiceCollection services)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(services);
|
|
services.TryAddSingleton<ILiveDashboardPollScheduler, SystemLiveDashboardPollScheduler>();
|
|
services.TryAddSingleton<ILiveDashboardFeedFactory, LiveDashboardFeedFactory>();
|
|
return services;
|
|
}
|
|
}
|