814 lines
35 KiB
C#
814 lines
35 KiB
C#
using System.Text.Json;
|
|
using AutoForge.Core.Simulation;
|
|
using AutoForge.Core.Vehicles;
|
|
|
|
namespace AutoForge.Diagnostics;
|
|
|
|
public sealed class SyntheticDiagnosticProtocolClient : IDiagnosticProtocolClient
|
|
{
|
|
private const long DefaultTimeoutTicks = 5;
|
|
private static readonly IReadOnlyDictionary<string, (string Unit, JsonValueKind Kind)> DynamicSignalShape =
|
|
new Dictionary<string, (string Unit, JsonValueKind Kind)>(StringComparer.Ordinal)
|
|
{
|
|
["engine.running"] = ("boolean", JsonValueKind.True),
|
|
["engine.speed"] = ("rpm", JsonValueKind.Number),
|
|
["vehicle.speed"] = ("m/s", JsonValueKind.Number),
|
|
["engine.throttle"] = ("ratio", JsonValueKind.Number),
|
|
["engine.load"] = ("ratio", JsonValueKind.Number),
|
|
["engine.torque"] = ("N*m", JsonValueKind.Number),
|
|
["engine.fuel-rate"] = ("kg/s", JsonValueKind.Number),
|
|
["engine.fuel-consumed"] = ("kg", JsonValueKind.Number),
|
|
["engine.temperature"] = ("degC", JsonValueKind.Number),
|
|
["vehicle.distance"] = ("m", JsonValueKind.Number),
|
|
["vehicle.acceleration"] = ("m/s^2", JsonValueKind.Number),
|
|
["driver.brake"] = ("ratio", JsonValueKind.Number),
|
|
["transmission.gear"] = ("gear", JsonValueKind.Number),
|
|
["transmission.shift-count"] = ("count", JsonValueKind.Number),
|
|
["transmission.coupling-slip"] = ("ratio", JsonValueKind.Number)
|
|
};
|
|
private readonly VehicleProfile _profile;
|
|
private readonly IDiagnosticTransport _transport;
|
|
private readonly IDiagnosticLogicalClock _clock;
|
|
private readonly DiagnosticTraceBuffer _trace;
|
|
private readonly int _protocolVersion;
|
|
private readonly DynamicsConfiguration? _dynamicsConfiguration;
|
|
private readonly SemaphoreSlim _exchangeGate = new(1, 1);
|
|
private long _correlationSequence;
|
|
|
|
public SyntheticDiagnosticProtocolClient(
|
|
VehicleProfile profile,
|
|
DiagnosticSessionIdentity session,
|
|
IDiagnosticTransport transport,
|
|
IDiagnosticLogicalClock clock,
|
|
int traceCapacity = 200,
|
|
int protocolVersion = 1,
|
|
DynamicsConfiguration? dynamicsConfiguration = null)
|
|
{
|
|
_profile = profile ?? throw new ArgumentNullException(nameof(profile));
|
|
Session = session ?? throw new ArgumentNullException(nameof(session));
|
|
_transport = transport ?? throw new ArgumentNullException(nameof(transport));
|
|
_clock = clock ?? throw new ArgumentNullException(nameof(clock));
|
|
if (protocolVersion is not (1 or 2))
|
|
{
|
|
throw new ArgumentOutOfRangeException(nameof(protocolVersion));
|
|
}
|
|
|
|
if (protocolVersion == 2 &&
|
|
(dynamicsConfiguration is null ||
|
|
session.DynamicsConfigurationIdentifier is null ||
|
|
session.DynamicsRunIdentifier is null ||
|
|
!StringComparer.Ordinal.Equals(
|
|
dynamicsConfiguration.ConfigurationIdentifier,
|
|
session.DynamicsConfigurationIdentifier)))
|
|
{
|
|
throw new ArgumentException("Dynamic protocol v2 requires the exact bound dynamics configuration and run identity.");
|
|
}
|
|
|
|
if (protocolVersion == 1 && dynamicsConfiguration is not null)
|
|
{
|
|
throw new ArgumentException("Static protocol v1 cannot be bound to a dynamics configuration.", nameof(dynamicsConfiguration));
|
|
}
|
|
|
|
_protocolVersion = protocolVersion;
|
|
_dynamicsConfiguration = dynamicsConfiguration;
|
|
_trace = new DiagnosticTraceBuffer(traceCapacity);
|
|
ExpectedEndpoints = Array.AsReadOnly(transport.ExpectedEndpoints.ToArray());
|
|
}
|
|
|
|
public DiagnosticSessionIdentity Session { get; }
|
|
public IReadOnlyList<DiagnosticEndpoint> ExpectedEndpoints { get; }
|
|
public DiagnosticTraceSnapshot Trace => _trace.Snapshot();
|
|
|
|
public async Task<DiscoveryResult> DiscoverAsync(CancellationToken cancellationToken = default)
|
|
{
|
|
var results = new List<DiscoveryEntry>(ExpectedEndpoints.Count);
|
|
foreach (var endpoint in ExpectedEndpoints)
|
|
{
|
|
var probe = await ExchangeAsync(
|
|
endpoint,
|
|
DiagnosticServices.Probe,
|
|
(data, _) =>
|
|
{
|
|
EnsureProperties(data, "moduleIdentifier", "implementedServices");
|
|
var moduleIdentifier = RequiredString(data, "moduleIdentifier");
|
|
ValidateModuleIdentifier(endpoint, moduleIdentifier);
|
|
var services = RequiredArray(data, "implementedServices")
|
|
.EnumerateArray()
|
|
.Select(item => item.ValueKind == JsonValueKind.String
|
|
? ValidateService(RequiredStringValue(item, "Implemented service"))
|
|
: throw new DiagnosticProtocolException("MALFORMED_RESPONSE", "Implemented services must be strings."))
|
|
.ToArray();
|
|
if (services.Length == 0 ||
|
|
services.Distinct(StringComparer.Ordinal).Count() != services.Length ||
|
|
!services.Contains(DiagnosticServices.Probe, StringComparer.Ordinal))
|
|
{
|
|
throw new DiagnosticProtocolException(
|
|
"INVALID_RESPONSE",
|
|
"Probe services must be unique and include the probe service.");
|
|
}
|
|
|
|
return new DiagnosticProbeResult(moduleIdentifier, services);
|
|
},
|
|
cancellationToken);
|
|
if (!probe.IsSuccess)
|
|
{
|
|
results.Add(new DiscoveryEntry(
|
|
endpoint,
|
|
probe,
|
|
null,
|
|
$"Identity read was not attempted because probe failed ({probe.Outcome})."));
|
|
continue;
|
|
}
|
|
|
|
if (!probe.Value!.ImplementedServices.Contains(DiagnosticServices.ReadIdentity, StringComparer.Ordinal))
|
|
{
|
|
results.Add(new DiscoveryEntry(
|
|
endpoint,
|
|
probe,
|
|
null,
|
|
$"Identity read was not attempted because '{DiagnosticServices.ReadIdentity}' was not advertised by the validated probe."));
|
|
continue;
|
|
}
|
|
|
|
var identity = await ReadIdentityAsync(endpoint, cancellationToken);
|
|
results.Add(new DiscoveryEntry(
|
|
endpoint,
|
|
probe,
|
|
identity));
|
|
}
|
|
|
|
return new DiscoveryResult(results);
|
|
}
|
|
|
|
public Task<DiagnosticOperationResult<ModuleIdentityResult>> ReadIdentityAsync(
|
|
DiagnosticEndpoint endpoint,
|
|
CancellationToken cancellationToken = default) =>
|
|
ExchangeAsync(
|
|
endpoint,
|
|
DiagnosticServices.ReadIdentity,
|
|
(data, _) =>
|
|
{
|
|
EnsureProperties(
|
|
data,
|
|
"moduleIdentifier",
|
|
"role",
|
|
"name",
|
|
"hardwareIdentifier",
|
|
"softwareIdentifier",
|
|
"firmwareIdentifier",
|
|
"calibrationIdentifier");
|
|
var identity = new ModuleIdentityResult(
|
|
RequiredString(data, "moduleIdentifier"),
|
|
endpoint.Address,
|
|
RequiredString(data, "role"),
|
|
RequiredString(data, "name"),
|
|
NullableString(data, "hardwareIdentifier"),
|
|
NullableString(data, "softwareIdentifier"),
|
|
NullableString(data, "firmwareIdentifier"),
|
|
NullableString(data, "calibrationIdentifier"));
|
|
ValidateIdentity(endpoint, identity);
|
|
return identity;
|
|
},
|
|
cancellationToken);
|
|
|
|
public Task<DiagnosticOperationResult<TroubleCodeReadResult>> ReadTroubleCodesAsync(
|
|
DiagnosticEndpoint endpoint,
|
|
CancellationToken cancellationToken = default) =>
|
|
ExchangeAsync(
|
|
endpoint,
|
|
DiagnosticServices.ReadTroubleCodes,
|
|
(data, _) =>
|
|
{
|
|
EnsureProperties(data, "moduleIdentifier", "codes");
|
|
var moduleIdentifier = RequiredString(data, "moduleIdentifier");
|
|
ValidateModuleIdentifier(endpoint, moduleIdentifier);
|
|
var codes = RequiredArray(data, "codes")
|
|
.EnumerateArray()
|
|
.Select(item =>
|
|
{
|
|
EnsureProperties(item, "code", "description");
|
|
return new DiagnosticTroubleCode(
|
|
RequiredString(item, "code"),
|
|
RequiredString(item, "description"),
|
|
moduleIdentifier);
|
|
})
|
|
.ToArray();
|
|
if (codes.Select(code => code.Code).Distinct(StringComparer.OrdinalIgnoreCase).Count() != codes.Length)
|
|
{
|
|
throw new DiagnosticProtocolException("INVALID_RESPONSE", "DTC codes must be unique within a module response.");
|
|
}
|
|
|
|
return new TroubleCodeReadResult(moduleIdentifier, codes);
|
|
},
|
|
cancellationToken);
|
|
|
|
public Task<DiagnosticOperationResult<TroubleCodeClearResult>> ClearTroubleCodesAsync(
|
|
DiagnosticEndpoint endpoint,
|
|
CancellationToken cancellationToken = default) =>
|
|
ExchangeAsync(
|
|
endpoint,
|
|
DiagnosticServices.ClearTroubleCodes,
|
|
(data, _) =>
|
|
{
|
|
EnsureProperties(data, "moduleIdentifier", "clearedCount");
|
|
var moduleIdentifier = RequiredString(data, "moduleIdentifier");
|
|
ValidateModuleIdentifier(endpoint, moduleIdentifier);
|
|
var count = RequiredInt32(data, "clearedCount");
|
|
if (count < 0)
|
|
{
|
|
throw new DiagnosticProtocolException("INVALID_RESPONSE", "Cleared count cannot be negative.");
|
|
}
|
|
|
|
return new TroubleCodeClearResult(moduleIdentifier, count);
|
|
},
|
|
cancellationToken);
|
|
|
|
public Task<DiagnosticOperationResult<SignalSnapshot>> ReadSignalsAsync(
|
|
DiagnosticEndpoint endpoint,
|
|
CancellationToken cancellationToken = default) =>
|
|
ExchangeAsync(
|
|
endpoint,
|
|
DiagnosticServices.ReadSignals,
|
|
(data, request) =>
|
|
{
|
|
EnsureProperties(
|
|
data,
|
|
_protocolVersion == 1
|
|
? ["moduleIdentifier", "logicalTimeTicks", "origin", "signals"]
|
|
: [
|
|
"moduleIdentifier",
|
|
"configurationIdentifier",
|
|
"runIdentifier",
|
|
"modelStepIndex",
|
|
"modelTimeSeconds",
|
|
"origin",
|
|
"captureLogicalTimeTicks",
|
|
"signals"
|
|
]);
|
|
var moduleIdentifier = RequiredString(data, "moduleIdentifier");
|
|
ValidateModuleIdentifier(endpoint, moduleIdentifier);
|
|
var origin = RequiredString(data, "origin");
|
|
long? modelStepIndex = null;
|
|
double? modelTimeSeconds = null;
|
|
string? modelConfigurationIdentifier = null;
|
|
string? modelRunIdentifier = null;
|
|
var logicalTime = request.LogicalTimeTicks;
|
|
if (_protocolVersion == 1)
|
|
{
|
|
if (RequiredInt64(data, "logicalTimeTicks") != request.LogicalTimeTicks ||
|
|
!StringComparer.Ordinal.Equals(origin, "SYNTHETIC_STATIC"))
|
|
{
|
|
throw new DiagnosticProtocolException(
|
|
"INVALID_RESPONSE",
|
|
"Static signal origin and snapshot time must match protocol v1 semantics.");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
modelConfigurationIdentifier = RequiredString(data, "configurationIdentifier");
|
|
modelRunIdentifier = RequiredString(data, "runIdentifier");
|
|
modelStepIndex = RequiredInt64(data, "modelStepIndex");
|
|
modelTimeSeconds = RequiredFiniteDouble(data, "modelTimeSeconds");
|
|
if (RequiredInt64(data, "captureLogicalTimeTicks") != request.LogicalTimeTicks)
|
|
{
|
|
throw new DiagnosticProtocolException(
|
|
"INVALID_RESPONSE",
|
|
"Dynamic diagnostic capture ticks must match the request start ticks.");
|
|
}
|
|
|
|
var expectedTime = modelStepIndex.Value * _dynamicsConfiguration!.Model.StepSeconds;
|
|
if (modelStepIndex.Value < 0 ||
|
|
Math.Abs(modelTimeSeconds.Value - expectedTime) > 1e-9 ||
|
|
!StringComparer.Ordinal.Equals(modelConfigurationIdentifier, Session.DynamicsConfigurationIdentifier) ||
|
|
!StringComparer.Ordinal.Equals(modelRunIdentifier, Session.DynamicsRunIdentifier) ||
|
|
!StringComparer.Ordinal.Equals(origin, "SYNTHETIC_DYNAMIC"))
|
|
{
|
|
throw new DiagnosticProtocolException(
|
|
"INVALID_RESPONSE",
|
|
"Dynamic snapshot model time, origin, run or configuration binding is invalid.");
|
|
}
|
|
}
|
|
|
|
var signals = RequiredArray(data, "signals").EnumerateArray().Select(item =>
|
|
{
|
|
EnsureProperties(item, "signalIdentifier", "value", "unit", "quality");
|
|
var signalIdentifier = RequiredString(item, "signalIdentifier");
|
|
var qualityText = RequiredString(item, "quality");
|
|
if (!Enum.TryParse<SignalQuality>(qualityText, ignoreCase: false, out var quality) ||
|
|
!Enum.IsDefined(quality))
|
|
{
|
|
throw new DiagnosticProtocolException("INVALID_RESPONSE", $"Signal quality '{qualityText}' is invalid.");
|
|
}
|
|
|
|
var value = Required(item, "value");
|
|
var unit = RequiredString(item, "unit");
|
|
if (_protocolVersion == 2)
|
|
{
|
|
ValidateDynamicSignal(signalIdentifier, value, unit, moduleIdentifier);
|
|
}
|
|
|
|
return new DiagnosticSignal(
|
|
signalIdentifier,
|
|
moduleIdentifier,
|
|
value.Clone(),
|
|
unit,
|
|
quality,
|
|
logicalTime,
|
|
origin,
|
|
modelStepIndex,
|
|
modelTimeSeconds,
|
|
modelConfigurationIdentifier,
|
|
modelRunIdentifier);
|
|
}).ToArray();
|
|
if (signals.Select(signal => signal.SignalIdentifier)
|
|
.Distinct(StringComparer.OrdinalIgnoreCase).Count() != signals.Length)
|
|
{
|
|
throw new DiagnosticProtocolException(
|
|
"INVALID_RESPONSE",
|
|
"Signal identifiers must be unique within a module snapshot.");
|
|
}
|
|
|
|
if (_protocolVersion == 2)
|
|
{
|
|
var expectedCount = StringComparer.OrdinalIgnoreCase.Equals(
|
|
moduleIdentifier,
|
|
_dynamicsConfiguration!.EngineModuleIdentifier)
|
|
? 12
|
|
: 5;
|
|
if (signals.Length != expectedCount)
|
|
{
|
|
throw new DiagnosticProtocolException(
|
|
"INVALID_RESPONSE",
|
|
$"Dynamic module snapshot must contain exactly {expectedCount} configured signals.");
|
|
}
|
|
}
|
|
|
|
return new SignalSnapshot(
|
|
moduleIdentifier,
|
|
signals,
|
|
modelStepIndex,
|
|
modelTimeSeconds,
|
|
modelConfigurationIdentifier,
|
|
modelRunIdentifier);
|
|
},
|
|
cancellationToken);
|
|
|
|
private async Task<DiagnosticOperationResult<T>> ExchangeAsync<T>(
|
|
DiagnosticEndpoint endpoint,
|
|
string service,
|
|
Func<JsonElement, SyntheticDiagnosticRequest, T> decode,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(endpoint);
|
|
ArgumentNullException.ThrowIfNull(decode);
|
|
if (!ExpectedEndpoints.Any(candidate =>
|
|
Same(candidate.ModuleIdentifier, endpoint.ModuleIdentifier) &&
|
|
Same(candidate.Address, endpoint.Address)))
|
|
{
|
|
return DiagnosticOperationResult<T>.Failure(
|
|
DiagnosticOutcome.ProtocolError,
|
|
"UNEXPECTED_ENDPOINT",
|
|
"The requested endpoint is not part of this session.");
|
|
}
|
|
|
|
try
|
|
{
|
|
await _exchangeGate.WaitAsync(cancellationToken).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
return DiagnosticOperationResult<T>.Failure(
|
|
DiagnosticOutcome.Cancelled,
|
|
"CANCELLED",
|
|
"Operation was cancelled while waiting for the session transport.");
|
|
}
|
|
|
|
try
|
|
{
|
|
return await ExchangeSerializedAsync(endpoint, service, decode, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
finally
|
|
{
|
|
_exchangeGate.Release();
|
|
}
|
|
}
|
|
|
|
private async Task<DiagnosticOperationResult<T>> ExchangeSerializedAsync<T>(
|
|
DiagnosticEndpoint endpoint,
|
|
string service,
|
|
Func<JsonElement, SyntheticDiagnosticRequest, T> decode,
|
|
CancellationToken cancellationToken)
|
|
{
|
|
var sequence = Interlocked.Increment(ref _correlationSequence);
|
|
var correlation = $"{Session.SessionIdentifier}-{sequence:D6}";
|
|
var startTicks = _clock.Ticks;
|
|
var request = new SyntheticDiagnosticRequest(
|
|
Session.SessionIdentifier,
|
|
Session.ProfileIdentifier,
|
|
Session.ProfileRevision,
|
|
Session.ConfigurationIdentifier,
|
|
correlation,
|
|
endpoint.Address,
|
|
service,
|
|
startTicks,
|
|
DefaultTimeoutTicks)
|
|
{
|
|
Version = _protocolVersion
|
|
};
|
|
var requestPayload = SyntheticProtocolV1.EncodeRequest(request);
|
|
TransportReply transportReply;
|
|
|
|
try
|
|
{
|
|
transportReply = await _transport.SendAsync(requestPayload, cancellationToken).ConfigureAwait(false);
|
|
}
|
|
catch (OperationCanceledException)
|
|
{
|
|
var endTicks = _clock.Ticks;
|
|
AddTrace(endpoint, correlation, service, startTicks, endTicks, requestPayload, ReadOnlyMemory<byte>.Empty, DiagnosticOutcome.Cancelled, null, "Operation was cancelled.");
|
|
return DiagnosticOperationResult<T>.Failure(DiagnosticOutcome.Cancelled, "CANCELLED", "Operation was cancelled.");
|
|
}
|
|
|
|
_clock.AdvanceBy(transportReply.ElapsedTicks);
|
|
var responsePayload = transportReply.Payload;
|
|
if (transportReply.Outcome != TransportOutcome.Response)
|
|
{
|
|
var outcome = transportReply.Outcome switch
|
|
{
|
|
TransportOutcome.NoResponse => DiagnosticOutcome.NoResponse,
|
|
TransportOutcome.Timeout => DiagnosticOutcome.Timeout,
|
|
TransportOutcome.Cancelled => DiagnosticOutcome.Cancelled,
|
|
_ => DiagnosticOutcome.ProtocolError
|
|
};
|
|
var code = transportReply.Outcome.ToString().ToUpperInvariant();
|
|
var error = transportReply.Detail ?? $"Transport completed with {outcome}.";
|
|
AddTrace(endpoint, correlation, service, startTicks, _clock.Ticks, requestPayload, ReadOnlyMemory<byte>.Empty, outcome, null, error);
|
|
return DiagnosticOperationResult<T>.Failure(outcome, code, error);
|
|
}
|
|
|
|
try
|
|
{
|
|
using var document = JsonDocument.Parse(responsePayload);
|
|
var root = document.RootElement;
|
|
ValidateResponseEnvelope(root, request);
|
|
var success = RequiredBoolean(root, "success");
|
|
if (!success)
|
|
{
|
|
var errorCode = RequiredString(root, "errorCode");
|
|
var message = RequiredString(root, "error");
|
|
AddTrace(endpoint, correlation, service, startTicks, _clock.Ticks, requestPayload, responsePayload, DiagnosticOutcome.NegativeResponse, errorCode, message);
|
|
return DiagnosticOperationResult<T>.Failure(DiagnosticOutcome.NegativeResponse, errorCode, message);
|
|
}
|
|
|
|
var data = Required(root, "data");
|
|
var value = decode(data, request);
|
|
AddTrace(endpoint, correlation, service, startTicks, _clock.Ticks, requestPayload, responsePayload, DiagnosticOutcome.PositiveResponse, Summarize(value), null);
|
|
return DiagnosticOperationResult<T>.Success(value);
|
|
}
|
|
catch (JsonException)
|
|
{
|
|
var error = $"Response is not valid synthetic protocol v{_protocolVersion} JSON.";
|
|
AddTrace(endpoint, correlation, service, startTicks, _clock.Ticks, requestPayload, responsePayload, DiagnosticOutcome.ProtocolError, null, error);
|
|
return DiagnosticOperationResult<T>.Failure(DiagnosticOutcome.ProtocolError, "MALFORMED_RESPONSE", error);
|
|
}
|
|
catch (DiagnosticProtocolException exception)
|
|
{
|
|
AddTrace(endpoint, correlation, service, startTicks, _clock.Ticks, requestPayload, responsePayload, DiagnosticOutcome.ProtocolError, null, exception.Message);
|
|
return DiagnosticOperationResult<T>.Failure(DiagnosticOutcome.ProtocolError, exception.FailureCode, exception.Message);
|
|
}
|
|
}
|
|
|
|
private void ValidateResponseEnvelope(JsonElement root, SyntheticDiagnosticRequest request)
|
|
{
|
|
if (root.ValueKind != JsonValueKind.Object || !SyntheticProtocolV1.HasUniqueProperties(root))
|
|
{
|
|
throw new DiagnosticProtocolException(
|
|
"MALFORMED_RESPONSE",
|
|
"Response objects must be valid JSON objects without duplicate properties.");
|
|
}
|
|
|
|
EnsureProperties(
|
|
root,
|
|
"version",
|
|
"sessionIdentifier",
|
|
"configurationIdentifier",
|
|
"correlationIdentifier",
|
|
"targetAddress",
|
|
"service",
|
|
"success",
|
|
"errorCode",
|
|
"error",
|
|
"data");
|
|
if (RequiredInt32(root, "version") != _protocolVersion)
|
|
{
|
|
throw new DiagnosticProtocolException(
|
|
"UNSUPPORTED_VERSION",
|
|
$"Response protocol version {_protocolVersion} was expected.");
|
|
}
|
|
|
|
if (!Same(RequiredString(root, "sessionIdentifier"), Session.SessionIdentifier) ||
|
|
!Same(RequiredString(root, "configurationIdentifier"), Session.ConfigurationIdentifier) ||
|
|
!Same(RequiredString(root, "correlationIdentifier"), request.CorrelationIdentifier) ||
|
|
!Same(RequiredString(root, "targetAddress"), request.TargetAddress) ||
|
|
!Same(RequiredString(root, "service"), request.Service))
|
|
{
|
|
throw new DiagnosticProtocolException(
|
|
"CORRELATION_MISMATCH",
|
|
"Response session, correlation, address or service did not match the request.");
|
|
}
|
|
|
|
if (RequiredBoolean(root, "success"))
|
|
{
|
|
if (Required(root, "errorCode").ValueKind != JsonValueKind.Null ||
|
|
Required(root, "error").ValueKind != JsonValueKind.Null ||
|
|
Required(root, "data").ValueKind != JsonValueKind.Object)
|
|
{
|
|
throw new DiagnosticProtocolException(
|
|
"INVALID_RESPONSE",
|
|
"Positive responses require null error fields and an object data payload.");
|
|
}
|
|
}
|
|
else
|
|
{
|
|
_ = RequiredString(root, "errorCode");
|
|
_ = RequiredString(root, "error");
|
|
if (Required(root, "data").ValueKind != JsonValueKind.Null)
|
|
{
|
|
throw new DiagnosticProtocolException(
|
|
"INVALID_RESPONSE",
|
|
"Negative responses require a typed error and null data.");
|
|
}
|
|
}
|
|
}
|
|
|
|
private void ValidateIdentity(DiagnosticEndpoint endpoint, ModuleIdentityResult identity)
|
|
{
|
|
ValidateModuleIdentifier(endpoint, identity.ModuleIdentifier);
|
|
var expected = _profile.GetModule(endpoint.ModuleIdentifier);
|
|
if (!Same(expected.Role, identity.Role) ||
|
|
!Same(expected.Name, identity.Name) ||
|
|
!SameOptional(expected.HardwareIdentifier, identity.HardwareIdentifier) ||
|
|
!SameOptional(expected.SoftwareIdentifier, identity.SoftwareIdentifier) ||
|
|
!SameOptional(expected.FirmwareIdentifier, identity.FirmwareIdentifier) ||
|
|
!SameOptional(expected.CalibrationIdentifier, identity.CalibrationIdentifier))
|
|
{
|
|
throw new DiagnosticProtocolException(
|
|
"IDENTITY_MISMATCH",
|
|
$"Response identity for module '{endpoint.ModuleIdentifier}' does not match the selected profile snapshot.");
|
|
}
|
|
}
|
|
|
|
private static void ValidateModuleIdentifier(DiagnosticEndpoint endpoint, string moduleIdentifier)
|
|
{
|
|
if (!Same(endpoint.ModuleIdentifier, moduleIdentifier))
|
|
{
|
|
throw new DiagnosticProtocolException(
|
|
"IDENTITY_MISMATCH",
|
|
$"Response module '{moduleIdentifier}' does not match expected module '{endpoint.ModuleIdentifier}'.");
|
|
}
|
|
}
|
|
|
|
private void AddTrace(
|
|
DiagnosticEndpoint endpoint,
|
|
string correlation,
|
|
string service,
|
|
long startTicks,
|
|
long endTicks,
|
|
ReadOnlyMemory<byte> request,
|
|
ReadOnlyMemory<byte> response,
|
|
DiagnosticOutcome outcome,
|
|
string? summary,
|
|
string? error) =>
|
|
_trace.Add(new DiagnosticTraceEntry(
|
|
Session,
|
|
endpoint.ModuleIdentifier,
|
|
endpoint.Address,
|
|
correlation,
|
|
service,
|
|
startTicks,
|
|
endTicks,
|
|
request,
|
|
response,
|
|
outcome,
|
|
summary,
|
|
error));
|
|
|
|
private static string Summarize<T>(T value) => value switch
|
|
{
|
|
string text => text,
|
|
DiagnosticProbeResult probe => $"Probe responded with {probe.ImplementedServices.Count} service(s)",
|
|
TroubleCodeReadResult dtcs => $"{dtcs.Codes.Count} DTC(s)",
|
|
TroubleCodeClearResult cleared => $"{cleared.ClearedCount} virtual DTC(s) cleared",
|
|
SignalSnapshot signals => $"{signals.Signals.Count} static signal(s)",
|
|
ModuleIdentityResult identity => $"Identity for {identity.ModuleIdentifier}",
|
|
_ => typeof(T).Name
|
|
};
|
|
|
|
private static JsonElement Required(JsonElement element, string property)
|
|
{
|
|
if (element.ValueKind != JsonValueKind.Object ||
|
|
!element.TryGetProperty(property, out var value))
|
|
{
|
|
throw new DiagnosticProtocolException("MALFORMED_RESPONSE", $"Required response property '{property}' is missing.");
|
|
}
|
|
|
|
return value;
|
|
}
|
|
|
|
private static void EnsureProperties(JsonElement element, params string[] requiredProperties)
|
|
{
|
|
if (element.ValueKind != JsonValueKind.Object)
|
|
{
|
|
throw new DiagnosticProtocolException("MALFORMED_RESPONSE", "Service payloads must be JSON objects.");
|
|
}
|
|
|
|
var allowed = new HashSet<string>(requiredProperties, StringComparer.Ordinal);
|
|
foreach (var property in element.EnumerateObject())
|
|
{
|
|
if (!allowed.Remove(property.Name))
|
|
{
|
|
throw new DiagnosticProtocolException(
|
|
"MALFORMED_RESPONSE",
|
|
$"Response contains an unknown property '{property.Name}'.");
|
|
}
|
|
}
|
|
|
|
if (allowed.Count != 0)
|
|
{
|
|
throw new DiagnosticProtocolException(
|
|
"MALFORMED_RESPONSE",
|
|
$"Response is missing required property '{allowed.First()}'.");
|
|
}
|
|
}
|
|
|
|
private static string RequiredStringValue(JsonElement value, string description)
|
|
{
|
|
if (value.ValueKind != JsonValueKind.String || value.GetString() is not { } text)
|
|
{
|
|
throw new DiagnosticProtocolException("MALFORMED_RESPONSE", $"{description} must be a string.");
|
|
}
|
|
|
|
return ValidateText(text, description);
|
|
}
|
|
|
|
private static string RequiredString(JsonElement element, string property)
|
|
{
|
|
return RequiredStringValue(Required(element, property), $"Response property '{property}'");
|
|
}
|
|
|
|
private static string ValidateText(string text, string description)
|
|
{
|
|
if (string.IsNullOrWhiteSpace(text) || !StringComparer.Ordinal.Equals(text, text.Trim()))
|
|
{
|
|
throw new DiagnosticProtocolException(
|
|
"INVALID_RESPONSE",
|
|
$"{description} must be nonblank text without surrounding whitespace.");
|
|
}
|
|
|
|
return text;
|
|
}
|
|
|
|
private static string ValidateService(string service)
|
|
{
|
|
if (service is not (DiagnosticServices.Probe or
|
|
DiagnosticServices.ReadIdentity or
|
|
DiagnosticServices.ReadTroubleCodes or
|
|
DiagnosticServices.ClearTroubleCodes or
|
|
DiagnosticServices.ReadSignals))
|
|
{
|
|
throw new DiagnosticProtocolException("INVALID_RESPONSE", $"Service '{service}' is not defined by protocol v1.");
|
|
}
|
|
|
|
return service;
|
|
}
|
|
|
|
private static string? NullableString(JsonElement element, string property)
|
|
{
|
|
var value = Required(element, property);
|
|
if (value.ValueKind == JsonValueKind.Null)
|
|
{
|
|
return null;
|
|
}
|
|
|
|
if (value.ValueKind != JsonValueKind.String)
|
|
{
|
|
throw new DiagnosticProtocolException("MALFORMED_RESPONSE", $"Response property '{property}' must be a string or null.");
|
|
}
|
|
|
|
return ValidateText(value.GetString()!, $"Response property '{property}'");
|
|
}
|
|
|
|
private static JsonElement RequiredArray(JsonElement element, string property)
|
|
{
|
|
var value = Required(element, property);
|
|
if (value.ValueKind != JsonValueKind.Array)
|
|
{
|
|
throw new DiagnosticProtocolException("MALFORMED_RESPONSE", $"Response property '{property}' must be an array.");
|
|
}
|
|
|
|
return value;
|
|
}
|
|
|
|
private static bool RequiredBoolean(JsonElement element, string property)
|
|
{
|
|
var value = Required(element, property);
|
|
if (value.ValueKind is not (JsonValueKind.True or JsonValueKind.False))
|
|
{
|
|
throw new DiagnosticProtocolException("MALFORMED_RESPONSE", $"Response property '{property}' must be a boolean.");
|
|
}
|
|
|
|
return value.GetBoolean();
|
|
}
|
|
|
|
private static int RequiredInt32(JsonElement element, string property)
|
|
{
|
|
var value = Required(element, property);
|
|
if (value.ValueKind != JsonValueKind.Number || !value.TryGetInt32(out var result))
|
|
{
|
|
throw new DiagnosticProtocolException("MALFORMED_RESPONSE", $"Response property '{property}' must be a 32-bit integer.");
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
private static long RequiredInt64(JsonElement element, string property)
|
|
{
|
|
var value = Required(element, property);
|
|
if (value.ValueKind != JsonValueKind.Number || !value.TryGetInt64(out var result))
|
|
{
|
|
throw new DiagnosticProtocolException("MALFORMED_RESPONSE", $"Response property '{property}' must be a 64-bit integer.");
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
private static double RequiredFiniteDouble(JsonElement element, string property)
|
|
{
|
|
var value = Required(element, property);
|
|
if (value.ValueKind != JsonValueKind.Number ||
|
|
!value.TryGetDouble(out var result) ||
|
|
!double.IsFinite(result))
|
|
{
|
|
throw new DiagnosticProtocolException("MALFORMED_RESPONSE", $"Response property '{property}' must be a finite number.");
|
|
}
|
|
|
|
return result;
|
|
}
|
|
|
|
private void ValidateDynamicSignal(
|
|
string signalIdentifier,
|
|
JsonElement value,
|
|
string unit,
|
|
string moduleIdentifier)
|
|
{
|
|
if (!DynamicSignalShape.TryGetValue(signalIdentifier, out var shape) ||
|
|
!StringComparer.Ordinal.Equals(unit, shape.Unit))
|
|
{
|
|
throw new DiagnosticProtocolException(
|
|
"INVALID_RESPONSE",
|
|
$"Dynamic signal '{signalIdentifier}' is unknown or has an invalid unit.");
|
|
}
|
|
|
|
var engineSignal = signalIdentifier is
|
|
"engine.running" or "engine.speed" or "engine.throttle" or "engine.load" or "engine.torque" or
|
|
"engine.fuel-rate" or "engine.fuel-consumed" or "engine.temperature" or "vehicle.speed" or
|
|
"vehicle.distance" or "vehicle.acceleration" or "driver.brake";
|
|
var expectedModule = engineSignal
|
|
? _dynamicsConfiguration!.EngineModuleIdentifier
|
|
: _dynamicsConfiguration!.TransmissionModuleIdentifier;
|
|
var sharedPowertrainSignal = signalIdentifier is "engine.speed" or "vehicle.speed";
|
|
if (!StringComparer.OrdinalIgnoreCase.Equals(moduleIdentifier, expectedModule) &&
|
|
!(sharedPowertrainSignal &&
|
|
StringComparer.OrdinalIgnoreCase.Equals(moduleIdentifier, _dynamicsConfiguration!.TransmissionModuleIdentifier)))
|
|
{
|
|
throw new DiagnosticProtocolException(
|
|
"INVALID_RESPONSE",
|
|
$"Dynamic signal '{signalIdentifier}' came from the wrong module.");
|
|
}
|
|
|
|
if (shape.Kind == JsonValueKind.True)
|
|
{
|
|
if (value.ValueKind is not (JsonValueKind.True or JsonValueKind.False))
|
|
{
|
|
throw new DiagnosticProtocolException("INVALID_RESPONSE", $"Dynamic signal '{signalIdentifier}' must be boolean.");
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
if (value.ValueKind != JsonValueKind.Number ||
|
|
!value.TryGetDouble(out var number) ||
|
|
!double.IsFinite(number))
|
|
{
|
|
throw new DiagnosticProtocolException("INVALID_RESPONSE", $"Dynamic signal '{signalIdentifier}' must be a finite JSON number.");
|
|
}
|
|
}
|
|
|
|
private static bool Same(string left, string right) =>
|
|
StringComparer.OrdinalIgnoreCase.Equals(left, right);
|
|
|
|
private static bool SameOptional(string? expected, string? actual) =>
|
|
expected is null ? actual is null : actual is not null && Same(expected, actual);
|
|
|
|
}
|