293 lines
11 KiB
C#
293 lines
11 KiB
C#
using System.Collections.ObjectModel;
|
|
using System.Text.Json;
|
|
using System.Text.Json.Serialization;
|
|
using AutoForge.Application.Features.Vehicles.Profiles;
|
|
using AutoForge.Core.Simulation;
|
|
using AutoForge.Core.Vehicles;
|
|
using Microsoft.Extensions.DependencyInjection;
|
|
|
|
namespace AutoForge.Application.Features.Vehicles.Simulation;
|
|
|
|
public sealed record DynamicsConfigurationReference(
|
|
string ConfigurationIdentifier,
|
|
string ProfileIdentifier,
|
|
int ProfileRevision,
|
|
string ModelIdentifier);
|
|
|
|
public sealed class DynamicsConfigurationException(string message, Exception? innerException = null)
|
|
: Exception(message, innerException);
|
|
|
|
public interface IDynamicsConfigurationService
|
|
{
|
|
DynamicsConfiguration CreateExample(string profileIdentifier, int profileRevision);
|
|
DynamicsConfiguration Import(string json);
|
|
IReadOnlyList<DynamicsConfigurationReference> List();
|
|
DynamicsConfiguration Select(string configurationIdentifier);
|
|
string Export(string configurationIdentifier);
|
|
}
|
|
|
|
public sealed class DynamicsConfigurationService : IDynamicsConfigurationService
|
|
{
|
|
private static readonly JsonSerializerOptions JsonOptions = new()
|
|
{
|
|
PropertyNamingPolicy = JsonNamingPolicy.CamelCase,
|
|
UnmappedMemberHandling = JsonUnmappedMemberHandling.Disallow,
|
|
WriteIndented = true,
|
|
Converters = { new JsonStringEnumConverter(JsonNamingPolicy.CamelCase) }
|
|
};
|
|
|
|
private readonly object _gate = new();
|
|
private readonly IVehicleProfileService _profiles;
|
|
private readonly Dictionary<string, DynamicsConfiguration> _configurations =
|
|
new(StringComparer.Ordinal);
|
|
|
|
public DynamicsConfigurationService(IVehicleProfileService profiles) =>
|
|
_profiles = profiles ?? throw new ArgumentNullException(nameof(profiles));
|
|
|
|
public DynamicsConfiguration CreateExample(string profileIdentifier, int profileRevision)
|
|
{
|
|
var profile = _profiles.Select(profileIdentifier, profileRevision);
|
|
var configuration = DynamicsConfiguration.CreateWarmBaseline(profile);
|
|
Register(configuration);
|
|
return configuration;
|
|
}
|
|
|
|
public DynamicsConfiguration Import(string json)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(json);
|
|
try
|
|
{
|
|
using var document = JsonDocument.Parse(json);
|
|
if (document.RootElement.ValueKind != JsonValueKind.Object || !HasUniqueProperties(document.RootElement))
|
|
{
|
|
throw new JsonException("Dynamics configuration must be a JSON object with no duplicate properties.");
|
|
}
|
|
|
|
ValidateDocumentShape(document.RootElement);
|
|
var configuration = JsonSerializer.Deserialize<DynamicsConfiguration>(json, JsonOptions)
|
|
?? throw new JsonException("Dynamics configuration cannot be null.");
|
|
VehicleProfile profile;
|
|
try
|
|
{
|
|
profile = _profiles.Select(configuration.ProfileIdentifier, configuration.ProfileRevision);
|
|
}
|
|
catch (VehicleProfileCatalogException exception)
|
|
{
|
|
throw new DynamicsConfigurationException(
|
|
$"Dynamics profile reference '{configuration.ProfileIdentifier}' revision {configuration.ProfileRevision} is not available: {exception.Message}",
|
|
exception);
|
|
}
|
|
|
|
try
|
|
{
|
|
configuration.ValidateAgainst(profile);
|
|
}
|
|
catch (ArgumentException exception)
|
|
{
|
|
throw new DynamicsConfigurationException(exception.Message, exception);
|
|
}
|
|
|
|
Register(configuration);
|
|
return configuration;
|
|
}
|
|
catch (JsonException exception)
|
|
{
|
|
throw new DynamicsConfigurationException($"Dynamics configuration JSON is invalid: {exception.Message}", exception);
|
|
}
|
|
catch (ArgumentException exception)
|
|
{
|
|
throw new DynamicsConfigurationException($"Dynamics configuration is invalid: {exception.Message}", exception);
|
|
}
|
|
catch (KeyNotFoundException exception)
|
|
{
|
|
throw new DynamicsConfigurationException(
|
|
$"Dynamics configuration references a module that is not present in the selected profile: {exception.Message}",
|
|
exception);
|
|
}
|
|
}
|
|
|
|
public IReadOnlyList<DynamicsConfigurationReference> List()
|
|
{
|
|
lock (_gate)
|
|
{
|
|
return Array.AsReadOnly(_configurations.Values
|
|
.OrderBy(configuration => configuration.ProfileIdentifier, StringComparer.OrdinalIgnoreCase)
|
|
.ThenBy(configuration => configuration.ProfileRevision)
|
|
.ThenBy(configuration => configuration.ConfigurationIdentifier, StringComparer.Ordinal)
|
|
.Select(configuration => new DynamicsConfigurationReference(
|
|
configuration.ConfigurationIdentifier,
|
|
configuration.ProfileIdentifier,
|
|
configuration.ProfileRevision,
|
|
configuration.ModelIdentifier))
|
|
.ToArray());
|
|
}
|
|
}
|
|
|
|
public DynamicsConfiguration Select(string configurationIdentifier)
|
|
{
|
|
ArgumentException.ThrowIfNullOrWhiteSpace(configurationIdentifier);
|
|
lock (_gate)
|
|
{
|
|
return _configurations.TryGetValue(configurationIdentifier, out var configuration)
|
|
? configuration
|
|
: throw new DynamicsConfigurationException(
|
|
$"Dynamics configuration '{configurationIdentifier}' has not been explicitly imported or created.");
|
|
}
|
|
}
|
|
|
|
public string Export(string configurationIdentifier) =>
|
|
JsonSerializer.Serialize(Select(configurationIdentifier), JsonOptions);
|
|
|
|
private void Register(DynamicsConfiguration configuration)
|
|
{
|
|
lock (_gate)
|
|
{
|
|
if (_configurations.TryGetValue(configuration.ConfigurationIdentifier, out var existing))
|
|
{
|
|
if (!StringComparer.Ordinal.Equals(ExportCanonical(existing), ExportCanonical(configuration)))
|
|
{
|
|
throw new DynamicsConfigurationException("A configuration fingerprint collision was detected.");
|
|
}
|
|
|
|
return;
|
|
}
|
|
|
|
_configurations.Add(configuration.ConfigurationIdentifier, configuration);
|
|
}
|
|
}
|
|
|
|
private static string ExportCanonical(DynamicsConfiguration configuration) =>
|
|
JsonSerializer.Serialize(configuration, JsonOptions);
|
|
|
|
private static bool HasUniqueProperties(JsonElement element)
|
|
{
|
|
if (element.ValueKind == JsonValueKind.Object)
|
|
{
|
|
var names = new HashSet<string>(StringComparer.Ordinal);
|
|
foreach (var property in element.EnumerateObject())
|
|
{
|
|
if (!names.Add(property.Name) || !HasUniqueProperties(property.Value))
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
}
|
|
else if (element.ValueKind == JsonValueKind.Array)
|
|
{
|
|
return element.EnumerateArray().All(HasUniqueProperties);
|
|
}
|
|
|
|
return true;
|
|
}
|
|
|
|
private static void ValidateDocumentShape(JsonElement root)
|
|
{
|
|
EnsureProperties(
|
|
root,
|
|
"formatVersion",
|
|
"profileIdentifier",
|
|
"profileRevision",
|
|
"vehicleIdentifier",
|
|
"engineModuleIdentifier",
|
|
"engineCalibrationReference",
|
|
"transmissionModuleIdentifier",
|
|
"transmissionCalibrationReference",
|
|
"modelIdentifier",
|
|
"modelVersion",
|
|
"model",
|
|
"initialConditions",
|
|
"scenario");
|
|
var model = root.GetProperty("model");
|
|
EnsureProperties(
|
|
model,
|
|
"stepSeconds",
|
|
"vehicleMassKilograms",
|
|
"wheelRadiusMeters",
|
|
"dragAreaSquareMeters",
|
|
"rollingResistanceCoefficient",
|
|
"airDensityKilogramsPerCubicMeter",
|
|
"gravityMetersPerSecondSquared",
|
|
"drivetrainEfficiency",
|
|
"maximumBrakeForceNewtons",
|
|
"idleSpeedRpm",
|
|
"maximumEngineSpeedRpm",
|
|
"warmIdleTargetRpm",
|
|
"launchSlipEndSpeedMetersPerSecond",
|
|
"idleFuelRateKilogramsPerSecond",
|
|
"fuelKilogramsPerJoule",
|
|
"ambientTemperatureCelsius",
|
|
"initialEngineTemperatureCelsius",
|
|
"equilibriumEngineTemperatureCelsius",
|
|
"thermalResponsePerSecond",
|
|
"engineTorqueCurve",
|
|
"forwardGearRatios",
|
|
"upshiftSpeedsRpm",
|
|
"downshiftSpeedsRpm",
|
|
"finalDriveRatio");
|
|
foreach (var point in RequireArray(model.GetProperty("engineTorqueCurve"), "engineTorqueCurve").EnumerateArray())
|
|
{
|
|
EnsureProperties(point, "engineSpeedRpm", "torqueNewtonMeters");
|
|
}
|
|
|
|
EnsureProperties(
|
|
root.GetProperty("initialConditions"),
|
|
"engineRunning",
|
|
"vehicleSpeedMetersPerSecond",
|
|
"gear",
|
|
"engineSpeedRpm",
|
|
"engineTemperatureCelsius",
|
|
"fuelConsumedKilograms",
|
|
"distanceMeters");
|
|
foreach (var phase in RequireArray(root.GetProperty("scenario"), "scenario").EnumerateArray())
|
|
{
|
|
EnsureProperties(phase, "kind", "targetSpeedMetersPerSecond", "durationSeconds");
|
|
}
|
|
}
|
|
|
|
private static void EnsureProperties(JsonElement element, params string[] expectedProperties)
|
|
{
|
|
if (element.ValueKind != JsonValueKind.Object)
|
|
{
|
|
throw new JsonException("Dynamics configuration objects must be JSON objects.");
|
|
}
|
|
|
|
var expected = new HashSet<string>(expectedProperties, StringComparer.Ordinal);
|
|
foreach (var property in element.EnumerateObject())
|
|
{
|
|
if (!expected.Remove(property.Name))
|
|
{
|
|
throw new JsonException($"Dynamics configuration contains an unknown property '{property.Name}'.");
|
|
}
|
|
}
|
|
|
|
if (expected.Count != 0)
|
|
{
|
|
throw new JsonException($"Dynamics configuration is missing required property '{expected.First()}'.");
|
|
}
|
|
}
|
|
|
|
private static JsonElement RequireArray(JsonElement element, string propertyName)
|
|
{
|
|
if (element.ValueKind != JsonValueKind.Array)
|
|
{
|
|
throw new JsonException($"Dynamics configuration property '{propertyName}' must be an array.");
|
|
}
|
|
|
|
return element;
|
|
}
|
|
}
|
|
|
|
public static class DynamicsConfigurationServiceCollectionExtensions
|
|
{
|
|
public static IServiceCollection AddAutoForgeDynamicsConfigurations(this IServiceCollection services)
|
|
{
|
|
ArgumentNullException.ThrowIfNull(services);
|
|
if (!services.Any(service => service.ServiceType == typeof(IDynamicsConfigurationService)))
|
|
{
|
|
services.AddSingleton<IDynamicsConfigurationService, DynamicsConfigurationService>();
|
|
}
|
|
|
|
return services;
|
|
}
|
|
}
|