98 lines
2.7 KiB
C#
98 lines
2.7 KiB
C#
using MyParking.Simulation.Commands;
|
|||
|
|
using MyParking.Simulation.Core;
|
||
|
|
|
||
|
|
var builder = WebApplication.CreateBuilder(args);
|
||
|
|
|
||
|
|
builder.Services.AddSingleton<SimulationWorld>();
|
||
|
|
builder.Services.AddSingleton<SimulationCommandDispatcher>();
|
||
|
|
builder.Services.AddHostedService<SimulationClock>();
|
||
|
|
|
||
|
|
var app = builder.Build();
|
||
|
|
|
||
|
|
app.UseDefaultFiles();
|
||
|
|
app.UseStaticFiles();
|
||
|
|
|
||
|
|
app.MapGet("/api/vehicles", (SimulationWorld world) =>
|
||
|
|
Results.Ok(world.GetSnapshot()));
|
||
|
|
|
||
|
|
app.MapGet(
|
||
|
|
"/api/actions",
|
||
|
|
(SimulationCommandDispatcher dispatcher) =>
|
||
|
|
Results.Ok(dispatcher.GetActions()));
|
||
|
|
|
||
|
|
app.MapGet("/api/configuration", (SimulationWorld world) =>
|
||
|
|
Results.Ok(world.GetConfiguration()));
|
||
|
|
|
||
|
|
app.MapPost(
|
||
|
|
"/api/configuration",
|
||
|
|
(MyParking.Simulation.Models.SimulationConfigurationDto configuration,
|
||
|
|
SimulationWorld world) =>
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
world.ApplyConfiguration(configuration);
|
||
|
|
return Results.Ok(world.GetConfiguration());
|
||
|
|
}
|
||
|
|
catch (ArgumentException exception)
|
||
|
|
{
|
||
|
|
return Results.BadRequest(new
|
||
|
|
{
|
||
|
|
message = exception.Message
|
||
|
|
});
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
app.MapPost(
|
||
|
|
"/api/vehicles/{vehicleId:int}/commands/{command}",
|
||
|
|
(int vehicleId, string command, SimulationCommandDispatcher dispatcher) =>
|
||
|
|
{
|
||
|
|
var result = dispatcher.Execute(vehicleId, command);
|
||
|
|
return result.Success
|
||
|
|
? Results.Ok(result)
|
||
|
|
: Results.BadRequest(result);
|
||
|
|
});
|
||
|
|
|
||
|
|
app.MapPost(
|
||
|
|
"/api/vehicles/{vehicleId:int}/manual-control",
|
||
|
|
(int vehicleId,
|
||
|
|
MyParking.Simulation.Models.ManualControlInputDto input,
|
||
|
|
SimulationWorld world) =>
|
||
|
|
{
|
||
|
|
try
|
||
|
|
{
|
||
|
|
var success = world.WithVehicle(
|
||
|
|
vehicleId,
|
||
|
|
vehicle => vehicle.ManualDrive(
|
||
|
|
input.Throttle,
|
||
|
|
input.Steering,
|
||
|
|
input.SpeedScale,
|
||
|
|
input.SteeringScale));
|
||
|
|
|
||
|
|
var result = new CommandResult(
|
||
|
|
success,
|
||
|
|
success
|
||
|
|
? $"车辆{vehicleId}虚拟遥控输入已更新。"
|
||
|
|
: $"车辆{vehicleId}舵轮尚未到位或输入无效。");
|
||
|
|
|
||
|
|
return success
|
||
|
|
? Results.Ok(result)
|
||
|
|
: Results.BadRequest(result);
|
||
|
|
}
|
||
|
|
catch (KeyNotFoundException exception)
|
||
|
|
{
|
||
|
|
return Results.NotFound(new CommandResult(
|
||
|
|
false,
|
||
|
|
exception.Message));
|
||
|
|
}
|
||
|
|
});
|
||
|
|
|
||
|
|
app.MapPost("/api/reset", (SimulationWorld world) =>
|
||
|
|
{
|
||
|
|
world.Reset();
|
||
|
|
return Results.Ok(new { message = "全部仿真车已复位。" });
|
||
|
|
});
|
||
|
|
|
||
|
|
app.MapFallbackToFile("index.html");
|
||
|
|
|
||
|
|
app.Run();
|