using System.Collections.ObjectModel; using System.Text.Json; using System.Text.RegularExpressions; using AutoForge.Core.ExecutionTargets; using AutoForge.Core.Simulation; using AutoForge.Core.Vehicles; namespace AutoForge.Diagnostics; public sealed class DiagnosticProviderDescriptor { public DiagnosticProviderDescriptor(ExecutionTargetDescriptor target, string displayName) { Target = target ?? throw new ArgumentNullException(nameof(target)); ArgumentException.ThrowIfNullOrWhiteSpace(displayName); DisplayName = displayName; } public ExecutionTargetDescriptor Target { get; } public string DisplayName { get; } } public sealed class DiagnosticSessionIdentity { public DiagnosticSessionIdentity( string sessionIdentifier, string profileIdentifier, int profileRevision, string vehicleIdentifier, ExecutionTargetDescriptor target, string? dynamicsConfigurationIdentifier = null, string? dynamicsRunIdentifier = null) { SessionIdentifier = Require(sessionIdentifier, nameof(sessionIdentifier)); ProfileIdentifier = Require(profileIdentifier, nameof(profileIdentifier)); if (profileRevision <= 0) { throw new ArgumentOutOfRangeException(nameof(profileRevision)); } ProfileRevision = profileRevision; VehicleIdentifier = Require(vehicleIdentifier, nameof(vehicleIdentifier)); Target = target ?? throw new ArgumentNullException(nameof(target)); if ((dynamicsConfigurationIdentifier is null) != (dynamicsRunIdentifier is null)) { throw new ArgumentException("Dynamics configuration and run identities must either both be present or both be absent."); } DynamicsConfigurationIdentifier = dynamicsConfigurationIdentifier is null ? null : Require(dynamicsConfigurationIdentifier, nameof(dynamicsConfigurationIdentifier)); DynamicsRunIdentifier = dynamicsRunIdentifier is null ? null : Require(dynamicsRunIdentifier, nameof(dynamicsRunIdentifier)); ConfigurationIdentifier = DynamicsConfigurationIdentifier is null ? $"profile:{ProfileIdentifier}@revision:{ProfileRevision}" : $"profile:{ProfileIdentifier}@revision:{ProfileRevision};dynamics:{DynamicsConfigurationIdentifier}"; } public string SessionIdentifier { get; } public string ProfileIdentifier { get; } public int ProfileRevision { get; } public string ConfigurationIdentifier { get; } public string VehicleIdentifier { get; } public ExecutionTargetDescriptor Target { get; } public string? DynamicsConfigurationIdentifier { get; } public string? DynamicsRunIdentifier { get; } private static string Require(string value, string parameterName) { ArgumentException.ThrowIfNullOrWhiteSpace(value, parameterName); if (!StringComparer.Ordinal.Equals(value, value.Trim())) { throw new ArgumentException("Values must not contain surrounding whitespace.", parameterName); } return value; } } public sealed class DiagnosticEndpoint { private static readonly Regex AddressPattern = new(@"\A[0-9A-Fa-f]{1,4}\z", RegexOptions.CultureInvariant | RegexOptions.Compiled); public DiagnosticEndpoint(string moduleIdentifier, string address) { ArgumentException.ThrowIfNullOrWhiteSpace(moduleIdentifier); if (!StringComparer.Ordinal.Equals(moduleIdentifier, moduleIdentifier.Trim())) { throw new ArgumentException("Module identifiers must not contain surrounding whitespace.", nameof(moduleIdentifier)); } ArgumentException.ThrowIfNullOrWhiteSpace(address); if (!StringComparer.Ordinal.Equals(address, address.Trim())) { throw new ArgumentException("Endpoint addresses must not contain surrounding whitespace.", nameof(address)); } if (!AddressPattern.IsMatch(address)) { throw new ArgumentException("Synthetic protocol addresses must be one to four hexadecimal digits.", nameof(address)); } ModuleIdentifier = moduleIdentifier; Address = address; } public string ModuleIdentifier { get; } public string Address { get; } } public interface IDiagnosticTransportFactory { DiagnosticProviderDescriptor Descriptor { get; } IDiagnosticTransport OpenTransport(VehicleProfile profile, DiagnosticSessionIdentity identity); } public interface IDynamicsControl : IAsyncDisposable { DynamicsRunStatus Status { get; } double PacingFactor { get; } Task StartAsync(CancellationToken cancellationToken = default); Task PauseAsync(CancellationToken cancellationToken = default); Task ResumeAsync(CancellationToken cancellationToken = default); Task StopAsync(CancellationToken cancellationToken = default); Task ResetAsync(CancellationToken cancellationToken = default); Task StepAsync(int stepCount = 1, CancellationToken cancellationToken = default); Task SetPacingFactorAsync(double factor, CancellationToken cancellationToken = default); Task RunScenarioAsync(CancellationToken cancellationToken = default); } public sealed record DynamicsSessionBinding(IDiagnosticTransport Transport, IDynamicsControl Control); public interface IDynamicsDiagnosticTransportFactory : IDiagnosticTransportFactory { DynamicsSessionBinding OpenDynamicsTransport( VehicleProfile profile, DiagnosticSessionIdentity identity, DynamicsConfiguration configuration); } public enum DiagnosticProviderFailure { ConfigurationNotFound, SessionConflict } public sealed class DiagnosticProviderException( DiagnosticProviderFailure failure, string message, Exception? innerException = null) : Exception(message, innerException) { public DiagnosticProviderFailure Failure { get; } = failure; } public interface IDiagnosticTransport : IAsyncDisposable { IReadOnlyList ExpectedEndpoints { get; } ValueTask SendAsync(ReadOnlyMemory request, CancellationToken cancellationToken); } public enum TransportOutcome { Response, NoResponse, Timeout, Cancelled } public sealed class TransportReply { private readonly byte[]? _payload; public TransportReply(TransportOutcome outcome, ReadOnlyMemory payload, long elapsedTicks, string? detail = null) { if (!Enum.IsDefined(outcome)) { throw new ArgumentOutOfRangeException(nameof(outcome)); } if (elapsedTicks < 0) { throw new ArgumentOutOfRangeException(nameof(elapsedTicks)); } if (outcome != TransportOutcome.Response && !payload.IsEmpty) { throw new ArgumentException("A non-response outcome cannot contain a response payload.", nameof(payload)); } Outcome = outcome; _payload = payload.IsEmpty ? null : payload.ToArray(); ElapsedTicks = elapsedTicks; Detail = detail; } public TransportOutcome Outcome { get; } public ReadOnlyMemory Payload => _payload ?? ReadOnlyMemory.Empty; public long ElapsedTicks { get; } public string? Detail { get; } } public enum DiagnosticOutcome { PositiveResponse, NegativeResponse, NoResponse, Timeout, Cancelled, ProtocolError } public sealed class DiagnosticOperationResult { private DiagnosticOperationResult( DiagnosticOutcome outcome, T? value, string? failureCode, string? error) { Outcome = outcome; Value = value; FailureCode = failureCode; Error = error; } public DiagnosticOutcome Outcome { get; } public T? Value { get; } public string? FailureCode { get; } public string? Error { get; } public bool IsSuccess => Outcome == DiagnosticOutcome.PositiveResponse; public static DiagnosticOperationResult Success(T value) => new(DiagnosticOutcome.PositiveResponse, value ?? throw new ArgumentNullException(nameof(value)), null, null); public static DiagnosticOperationResult Failure(DiagnosticOutcome outcome, string code, string message) { if (outcome == DiagnosticOutcome.PositiveResponse) { throw new ArgumentOutOfRangeException(nameof(outcome)); } return new DiagnosticOperationResult(outcome, default, code, message); } } public sealed record ModuleIdentityResult( string ModuleIdentifier, string Address, string Role, string Name, string? HardwareIdentifier, string? SoftwareIdentifier, string? FirmwareIdentifier, string? CalibrationIdentifier); public sealed class DiagnosticProbeResult { public DiagnosticProbeResult(string moduleIdentifier, IEnumerable implementedServices) { ArgumentException.ThrowIfNullOrWhiteSpace(moduleIdentifier); ArgumentNullException.ThrowIfNull(implementedServices); ModuleIdentifier = moduleIdentifier; ImplementedServices = Array.AsReadOnly(implementedServices.ToArray()); } public string ModuleIdentifier { get; } public IReadOnlyList ImplementedServices { get; } } public enum DiagnosticIdentityStatus { NotAttempted, Verified, Unavailable } public sealed class DiscoveryEntry { public DiscoveryEntry( DiagnosticEndpoint endpoint, DiagnosticOperationResult probe, DiagnosticOperationResult? identityResult, string? identityNotAttemptedReason = null) { Endpoint = endpoint ?? throw new ArgumentNullException(nameof(endpoint)); Probe = probe ?? throw new ArgumentNullException(nameof(probe)); if (probe.IsSuccess != (probe.Value is not null)) { throw new ArgumentException("Probe result value must match its success outcome.", nameof(probe)); } if (!probe.IsSuccess && identityResult is not null) { throw new ArgumentException("Identity cannot be attempted when the probe did not succeed.", nameof(identityResult)); } if (identityResult is not null && !probe.Value!.ImplementedServices.Contains( DiagnosticServices.ReadIdentity, StringComparer.Ordinal)) { throw new ArgumentException("Identity cannot be attempted when the probe did not advertise the service.", nameof(identityResult)); } if (identityResult is not null && identityResult.IsSuccess != (identityResult.Value is not null)) { throw new ArgumentException("Identity result value must match its success outcome.", nameof(identityResult)); } if (identityResult is null) { ArgumentException.ThrowIfNullOrWhiteSpace(identityNotAttemptedReason); } if (identityResult is not null && identityNotAttemptedReason is not null) { throw new ArgumentException("An identity attempt cannot also have a not-attempted reason.", nameof(identityNotAttemptedReason)); } if (!Enum.IsDefined(probe.Outcome) || identityResult is not null && !Enum.IsDefined(identityResult.Outcome)) { throw new ArgumentOutOfRangeException(nameof(probe), "Discovery phases must use defined diagnostic outcomes."); } Probe = probe; IdentityResult = identityResult; IdentityNotAttemptedReason = identityNotAttemptedReason; } public DiagnosticEndpoint Endpoint { get; } public DiagnosticOperationResult Probe { get; } public DiagnosticOutcome ProbeOutcome => Probe.Outcome; public string? ProbeError => Probe.Error; public bool ProbeSucceeded => Probe.IsSuccess; public IReadOnlyList ImplementedServices => Probe.Value?.ImplementedServices ?? Array.Empty(); public DiagnosticOperationResult? IdentityResult { get; } public ModuleIdentityResult? Identity => IdentityResult?.Value; public DiagnosticIdentityStatus IdentityStatus => IdentityResult switch { null => DiagnosticIdentityStatus.NotAttempted, { IsSuccess: true } => DiagnosticIdentityStatus.Verified, _ => DiagnosticIdentityStatus.Unavailable }; public DiagnosticOutcome? IdentityOutcome => IdentityResult?.Outcome; public string? IdentityError => IdentityResult?.Error ?? IdentityNotAttemptedReason; public string? IdentityNotAttemptedReason { get; } } public sealed class DiscoveryResult { public DiscoveryResult(IEnumerable endpoints) { ArgumentNullException.ThrowIfNull(endpoints); Endpoints = Array.AsReadOnly(endpoints.ToArray()); } public IReadOnlyList Endpoints { get; } public IReadOnlyList ValidatedProbes => Array.AsReadOnly(Endpoints.Where(endpoint => endpoint.ProbeSucceeded).ToArray()); public IReadOnlyList IdentifiedModules => Array.AsReadOnly(Endpoints.Where(endpoint => endpoint.Identity is not null).Select(endpoint => endpoint.Identity!).ToArray()); public int ExpectedEndpointCount => Endpoints.Count; public int ValidatedProbeCount => ValidatedProbes.Count; public int IdentifiedModuleCount => IdentifiedModules.Count; } public sealed record DiagnosticTroubleCode(string Code, string Description, string SourceModuleIdentifier); public sealed class TroubleCodeReadResult { public TroubleCodeReadResult(string moduleIdentifier, IEnumerable codes) { ModuleIdentifier = moduleIdentifier; Codes = Array.AsReadOnly(codes.ToArray()); } public string ModuleIdentifier { get; } public IReadOnlyList Codes { get; } } public sealed record TroubleCodeClearResult(string ModuleIdentifier, int ClearedCount); public enum SignalQuality { Good, Uncertain, Unknown } public sealed record DiagnosticSignal( string SignalIdentifier, string ModuleIdentifier, JsonElement Value, string Unit, SignalQuality Quality, long LogicalTimeTicks, string Origin, long? ModelStepIndex = null, double? ModelTimeSeconds = null, string? ModelConfigurationIdentifier = null, string? ModelRunIdentifier = null); public sealed class SignalSnapshot { public SignalSnapshot( string moduleIdentifier, IEnumerable signals, long? modelStepIndex = null, double? modelTimeSeconds = null, string? modelConfigurationIdentifier = null, string? modelRunIdentifier = null) { ModuleIdentifier = moduleIdentifier; Signals = Array.AsReadOnly(signals.ToArray()); ModelStepIndex = modelStepIndex; ModelTimeSeconds = modelTimeSeconds; ModelConfigurationIdentifier = modelConfigurationIdentifier; ModelRunIdentifier = modelRunIdentifier; } public string ModuleIdentifier { get; } public IReadOnlyList Signals { get; } public long? ModelStepIndex { get; } public double? ModelTimeSeconds { get; } public string? ModelConfigurationIdentifier { get; } public string? ModelRunIdentifier { get; } } public sealed class DiagnosticTraceEntry { private readonly byte[] _requestPayload; private readonly byte[]? _responsePayload; public DiagnosticTraceEntry( DiagnosticSessionIdentity session, string moduleIdentifier, string address, string correlationIdentifier, string service, long startLogicalTicks, long endLogicalTicks, ReadOnlyMemory requestPayload, ReadOnlyMemory responsePayload, DiagnosticOutcome outcome, string? decodedSummary, string? error) { Session = session; ModuleIdentifier = moduleIdentifier; Address = address; CorrelationIdentifier = correlationIdentifier; Service = service; StartLogicalTicks = startLogicalTicks; EndLogicalTicks = endLogicalTicks; _requestPayload = requestPayload.ToArray(); _responsePayload = responsePayload.IsEmpty ? null : responsePayload.ToArray(); Outcome = outcome; DecodedSummary = decodedSummary; Error = error; } public DiagnosticSessionIdentity Session { get; } public string ModuleIdentifier { get; } public string Address { get; } public string CorrelationIdentifier { get; } public string Service { get; } public long StartLogicalTicks { get; } public long EndLogicalTicks { get; } public ReadOnlyMemory RequestPayload => _requestPayload.ToArray(); public ReadOnlyMemory? ResponsePayload => _responsePayload is null ? (ReadOnlyMemory?)null : new ReadOnlyMemory(_responsePayload.ToArray()); public DiagnosticOutcome Outcome { get; } public string? DecodedSummary { get; } public string? Error { get; } } public sealed class DiagnosticTraceSnapshot { public DiagnosticTraceSnapshot(IEnumerable entries, long droppedRecordCount) { Entries = new ReadOnlyCollection(entries.ToArray()); DroppedRecordCount = droppedRecordCount; } public IReadOnlyList Entries { get; } public long DroppedRecordCount { get; } } public sealed class DiagnosticOperationObservation { public DiagnosticOperationObservation( DiagnosticTraceEntry trace, SignalSnapshot? signalSnapshot) { Trace = trace ?? throw new ArgumentNullException(nameof(trace)); SignalSnapshot = signalSnapshot is null ? null : new SignalSnapshot( signalSnapshot.ModuleIdentifier, signalSnapshot.Signals.Select(signal => signal with { Value = signal.Value.Clone() }), signalSnapshot.ModelStepIndex, signalSnapshot.ModelTimeSeconds, signalSnapshot.ModelConfigurationIdentifier, signalSnapshot.ModelRunIdentifier); } public DiagnosticTraceEntry Trace { get; } public SignalSnapshot? SignalSnapshot { get; } } public interface IDiagnosticOperationObservationSource { int ProtocolVersion { get; } string? ObservationDispatchError { get; } IDisposable Subscribe(Action observer); } public sealed class DiagnosticTraceBuffer { private readonly object _gate = new(); private readonly Queue _entries = new(); public DiagnosticTraceBuffer(int capacity) { if (capacity <= 0) { throw new ArgumentOutOfRangeException(nameof(capacity)); } Capacity = capacity; } public int Capacity { get; } public long DroppedRecordCount { get; private set; } public void Add(DiagnosticTraceEntry entry) { ArgumentNullException.ThrowIfNull(entry); lock (_gate) { if (_entries.Count == Capacity) { _entries.Dequeue(); DroppedRecordCount++; } _entries.Enqueue(entry); } } public DiagnosticTraceSnapshot Snapshot() { lock (_gate) { return new DiagnosticTraceSnapshot(_entries, DroppedRecordCount); } } } public interface IDiagnosticLogicalClock { long Ticks { get; } void AdvanceBy(long ticks); } public sealed class DiagnosticLogicalClock : IDiagnosticLogicalClock { private long _ticks; public long Ticks => Interlocked.Read(ref _ticks); public void AdvanceBy(long ticks) { if (ticks < 0) { throw new ArgumentOutOfRangeException(nameof(ticks)); } Interlocked.Add(ref _ticks, ticks); } } public static class DiagnosticServices { public const string Probe = "probe"; public const string ReadIdentity = "read.identity"; public const string ReadTroubleCodes = "read.dtcs"; public const string ClearTroubleCodes = "clear.dtcs"; public const string ReadSignals = "read.signals"; } public interface IDiagnosticProtocolClient { DiagnosticSessionIdentity Session { get; } IReadOnlyList ExpectedEndpoints { get; } DiagnosticTraceSnapshot Trace { get; } Task DiscoverAsync(CancellationToken cancellationToken = default); Task> ReadIdentityAsync(DiagnosticEndpoint endpoint, CancellationToken cancellationToken = default); Task> ReadTroubleCodesAsync(DiagnosticEndpoint endpoint, CancellationToken cancellationToken = default); Task> ClearTroubleCodesAsync(DiagnosticEndpoint endpoint, CancellationToken cancellationToken = default); Task> ReadSignalsAsync(DiagnosticEndpoint endpoint, CancellationToken cancellationToken = default); }