using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using static Lab505.Shared.RobotPositions; using System.Globalization; using System.Net; using System.Text; using System.Text.Json; namespace Lab505.Sim; /// /// Mock HTTP Server mô phỏng VDA5050 API /// public class VdaSimulationHostedService : IHostedService, IDisposable { private HttpListener? _listener; private readonly ILogger _logger; private readonly Dictionary _robots; private readonly JsonSerializerOptions _jsonOptions; private CancellationTokenSource? _cts; private Task? _serverTask; private readonly int _port; private bool _isRunning; public bool IsRunning => _isRunning; public VdaSimulationHostedService(ILogger logger, int port = 7333) { _logger = logger; _port = port; _jsonOptions = new JsonSerializerOptions { PropertyNameCaseInsensitive = true, WriteIndented = true }; // Initialize mock robots with their default positions _robots = new Dictionary { ["AMR2WS"] = new RobotState { RobotId = "AMR2WS", X = AMR_CAP2_X, Y = AMR_CAP2_Y, Theta = 0, IsOnline = true, NewBaseRequest = true }, ["IMR"] = new RobotState { RobotId = "IMR", X = IMR_C1_X, Y = IMR_C1_Y, Theta = 0, IsOnline = true, NewBaseRequest = true } }; } public Task StartAsync(CancellationToken cancellationToken) { Start(); return Task.CompletedTask; } public Task StopAsync(CancellationToken cancellationToken) { Stop(); return Task.CompletedTask; } public void Start() { if (_isRunning) { _logger.LogWarning("VDA Mock Server already running"); return; } _listener = new HttpListener(); _listener.Prefixes.Add($"http://127.0.0.1:{_port}/"); _listener.Start(); _cts = new CancellationTokenSource(); _serverTask = Task.Run(() => HandleRequestsAsync(_cts.Token)); _isRunning = true; _logger.LogInformation("VDA Mock Server started on {Prefixes}", string.Join(", ", _listener.Prefixes)); } public void Stop() { if (!_isRunning) { _logger.LogWarning("VDA Mock Server not running"); return; } _cts?.Cancel(); _cts?.Dispose(); _cts = null; _serverTask?.Wait(TimeSpan.FromSeconds(5)); _serverTask = null; try { _listener?.Stop(); _listener?.Close(); } catch { } _listener = null; _isRunning = false; _logger.LogInformation("VDA Mock Server stopped"); } private async Task HandleRequestsAsync(CancellationToken cancellationToken) { while (!cancellationToken.IsCancellationRequested && _listener != null) { try { var context = await _listener.GetContextAsync(); _ = Task.Run(() => ProcessRequestAsync(context), cancellationToken); } catch (HttpListenerException) when (cancellationToken.IsCancellationRequested) { break; } catch (ObjectDisposedException) { break; } catch (Exception ex) { if (!cancellationToken.IsCancellationRequested) _logger.LogError(ex, "Error accepting request"); } } } private async Task ProcessRequestAsync(HttpListenerContext context) { var request = context.Request; var response = context.Response; try { _logger.LogDebug("{Method} {Url}", request.HttpMethod, request.Url?.PathAndQuery); var path = request.Url?.AbsolutePath ?? ""; var method = request.HttpMethod; object? result = null; // Route handling if (method == "GET" && path.StartsWith("/api/robotmanager/State/")) { var robotId = path.Split('/').Last(); result = HandleGetState(robotId); } else if (method == "POST" && path == "/api/AWC200/MoveTo") { var body = await ReadRequestBodyAsync(request); result = await HandleMoveToAsync(body); } else if (method == "POST" && path == "/api/robotmanager/instantactions") { var body = await ReadRequestBodyAsync(request); result = await HandleInstantActionAsync(body); } else if (method == "DELETE" && path.StartsWith("/api/AWC200/MoveTo/")) { var robotId = path.Split('/').Last(); result = HandleCancel(robotId); } else { response.StatusCode = 404; result = new { error = "Endpoint not found" }; } // Send response if (result != null) { response.ContentType = "application/json"; response.StatusCode = response.StatusCode == 0 ? 200 : response.StatusCode; var json = JsonSerializer.Serialize(result, _jsonOptions); var buffer = Encoding.UTF8.GetBytes(json); response.ContentLength64 = buffer.Length; await response.OutputStream.WriteAsync(buffer); } } catch (Exception ex) { _logger.LogError(ex, "Error processing request"); response.StatusCode = 500; var error = new { error = ex.Message }; var json = JsonSerializer.Serialize(error, _jsonOptions); var buffer = Encoding.UTF8.GetBytes(json); response.ContentLength64 = buffer.Length; await response.OutputStream.WriteAsync(buffer); } finally { response.Close(); } } private static async Task ReadRequestBodyAsync(HttpListenerRequest request) { using var reader = new StreamReader(request.InputStream, request.ContentEncoding); return await reader.ReadToEndAsync(); } #region Handlers private object HandleGetState(string robotId) { if (!_robots.TryGetValue(robotId, out var state)) { return new ApiResult { IsSuccess = false, Message = $"Robot {robotId} not found" }; } // Snapshot dưới lock — tránh "Collection was modified" khi task nền Add/Remove // đúng lúc poller đọc state. VdaActionState[] actionStatesSnapshot; lock (state.ActionStates) actionStatesSnapshot = state.ActionStates.ToArray(); return new RobotStateResult { IsSuccess = true, Message = "OK", Data = new RobotStateData { RobotId = robotId, MapId = Guid.NewGuid(), IsOnline = state.IsOnline, State = "READY", StateMsg = new VdaStateMsg { HeaderId = (uint)DateTime.UtcNow.Ticks, Timestamp = DateTime.UtcNow.ToString("o"), Version = "2.0", Manufacturer = "MockManufacturer", SerialNumber = robotId, OrderId = state.CurrentOrderId, OrderUpdateId = state.OrderUpdateId, LastNodeId = state.LastNodeId, LastNodeSequenceId = 0, Driving = state.IsDriving, Paused = state.Paused, NewBaseRequest = state.NewBaseRequest, DistanceSinceLastNode = 0, OperatingMode = "AUTOMATIC", AgvPosition = new VdaAgvPosition { X = state.X, Y = state.Y, Theta = state.Theta, MapId = "map001", PositionInitialized = true }, ActionStates = actionStatesSnapshot, Errors = [] }, VisualizationMsg = new VdaVisualizationMsg { HeaderId = (uint)DateTime.UtcNow.Ticks, Timestamp = DateTime.UtcNow.ToString("o"), Version = "2.0", Manufacturer = "MockManufacturer", SerialNumber = robotId, AgvPosition = new VdaAgvPosition { X = state.X, Y = state.Y, Theta = state.Theta, MapId = "map001", PositionInitialized = true } } } }; } private async Task HandleMoveToAsync(string requestBody) { var request = JsonSerializer.Deserialize(requestBody, _jsonOptions); if (request == null || string.IsNullOrEmpty(request.RobotId)) { return new ApiResult { IsSuccess = false, Message = "Invalid request" }; } if (!_robots.TryGetValue(request.RobotId, out var state)) { return new ApiResult { IsSuccess = false, Message = $"Robot {request.RobotId} not found" }; } _logger.LogInformation("Mock: Moving {RobotId} to {Target}", request.RobotId, request.RoomName); // VDA5050: NewBaseRequest = false when movement starts (robot busy) state.NewBaseRequest = false; state.CurrentOrderId = Guid.NewGuid().ToString(); state.OrderUpdateId++; state.LastNodeId = request.RoomName; state.IsDriving = true; // Simulate movement (~3s total) _ = Task.Run(async () => { // Get target position from robot-specific predefined locations var (targetX, targetY) = GetLocationCoordinates(request.RoomName, request.RobotId); // Simulate gradual movement over ~10 seconds var steps = 100; for (int i = 0; i < steps; i++) { await Task.Delay(100); // 100 x 100ms = 10s // Pause (startPause): đóng băng vị trí, không tiến bước cho tới khi resume. // Thoát nếu bị cancel (HandleCancel đặt IsDriving=false / Paused=false). while (state.Paused && state.IsDriving) await Task.Delay(100); // Cancel: dừng tại chỗ, không snap tới đích (HandleCancel đã set NBR=true). if (!state.IsDriving) return; state.X = state.X + (targetX - state.X) / (steps - i); state.Y = state.Y + (targetY - state.Y) / (steps - i); } state.X = targetX; state.Y = targetY; state.IsDriving = false; // VDA5050: NewBaseRequest = true when movement complete (robot ready) state.NewBaseRequest = true; _logger.LogInformation("Mock: {RobotId} arrived at {Target} ({X}, {Y}), NewBaseRequest=true", request.RobotId, request.RoomName, targetX, targetY); }); return new ApiResult { IsSuccess = true, Message = "MoveTo command accepted" }; } private async Task HandleInstantActionAsync(string requestBody) { var request = JsonSerializer.Deserialize(requestBody, _jsonOptions); if (request == null || string.IsNullOrEmpty(request.RobotId) || request.Action == null) { return new ApiResult { IsSuccess = false, Message = "Invalid request" }; } if (!_robots.TryGetValue(request.RobotId, out var state)) { return new ApiResult { IsSuccess = false, Message = $"Robot {request.RobotId} not found" }; } var action = request.Action; _logger.LogInformation("Mock: {RobotId} executing {ActionType}", request.RobotId, action.ActionType); // VDA5050: NewBaseRequest stays TRUE during WAITING and INITIALIZING. // Only movement-type actions (UnDockFromStation) set it FALSE during RUNNING. // Station-type actions (Load, UnLoad, DockToStation, PickUp, MutedSafety) keep it TRUE. // Movement actions: robot physically moves → blocks new base requests during RUNNING static bool IsMovementAction(string actionType) => actionType is "UnDockFromStation" or "UndockFromStation"; var actionState = new VdaActionState { ActionID = action.ActionId, ActionType = action.ActionType, ActionDescription = action.ActionDescription, ActionStatus = "WAITING" }; lock (state.ActionStates) state.ActionStates.Add(actionState); _ = Task.Run(async () => { await Task.Delay(200); actionState.ActionStatus = "INITIALIZING"; // NewBaseRequest still TRUE here — robot is preparing but not yet blocking await Task.Delay(300); actionState.ActionStatus = "RUNNING"; // Only movement actions set NewBaseRequest = false during RUNNING if (IsMovementAction(action.ActionType)) state.NewBaseRequest = false; switch (action.ActionType) { case "UnDockFromStation": case "UndockFromStation": // IMR: dùng distance param (lùi theo trục X, Theta=0) // AMR: dùng vị trí undock được định nghĩa sẵn theo trạm đang đậu // (tránh sai hướng do Theta=0 cố định trong sim) if (request.RobotId == "IMR") { var distance = GetActionParameter(action, "distance", -0.5); state.X += distance * Math.Cos(state.Theta); state.Y += distance * Math.Sin(state.Theta); } else // AMR { if (Math.Abs(state.X - AMR_CAP1_X) < POS_TOL && Math.Abs(state.Y - AMR_CAP1_Y) < POS_TOL) { state.X = AMR_UNDOCK_CAP1_X; state.Y = AMR_UNDOCK_CAP1_Y; } else if (Math.Abs(state.X - AMR_CAP2_X) < POS_TOL && Math.Abs(state.Y - AMR_CAP2_Y) < POS_TOL) { state.X = AMR_UNDOCK_CAP2_X; state.Y = AMR_UNDOCK_CAP2_Y; } else { // Vị trí không xác định — fallback theta-based var distance = GetActionParameter(action, "distance", -0.5); state.X += distance * Math.Cos(state.Theta); state.Y += distance * Math.Sin(state.Theta); } } await Task.Delay(9500); break; case "DockToStation": // Robot drives forward by 'distance' meters (reverse of undock) var dockDist = GetActionParameter(action, "distance", 1.2); state.X += dockDist * Math.Cos(state.Theta); state.Y += dockDist * Math.Sin(state.Theta); await Task.Delay(9500); break; case "startPause": // Robot tạm dừng — đặt cờ Paused, hoàn thành nhanh state.Paused = true; await Task.Delay(200); break; case "stopPause": // Robot tiếp tục — bỏ cờ Paused, hoàn thành nhanh state.Paused = false; await Task.Delay(200); break; case "initPosition": // Đặt lại pose (x, y, theta) tức thì state.X = GetActionParameter(action, "x", state.X); state.Y = GetActionParameter(action, "y", state.Y); state.Theta = GetActionParameter(action, "theta", state.Theta); await Task.Delay(200); break; case "Load": case "UpLoad": case "UnLoad": case "PickUp": case "MutedSafety": case "Muted Safety": case "MuteOn": case "MuteOff": // Station actions — robot stays put, NewBaseRequest stays TRUE await Task.Delay(9500); break; default: await Task.Delay(9500); break; } actionState.ActionStatus = "FINISHED"; state.NewBaseRequest = true; _logger.LogInformation( "Mock: {RobotId} {ActionType} FINISHED, NewBaseRequest=true", request.RobotId, action.ActionType); // Keep FINISHED state long enough for the 300 ms VDA poller to catch it await Task.Delay(5000); lock (state.ActionStates) state.ActionStates.Remove(actionState); }); return new ApiResult { IsSuccess = true, Message = $"{action.ActionType} command accepted" }; } private object HandleCancel(string robotId) { if (!_robots.TryGetValue(robotId, out var state)) return new ApiResult { IsSuccess = false, Message = $"Robot {robotId} not found" }; _logger.LogInformation("Mock: Canceling order for {RobotId}", robotId); // VDA5050: chuyển tất cả action đang active → ABORTED // DualCommandMonitor đang chờ sẽ nhận được ABORTED trong lần poll tiếp theo (~300ms) lock (state.ActionStates) { foreach (var a in state.ActionStates) { if (a.ActionStatus is "WAITING" or "INITIALIZING" or "RUNNING") a.ActionStatus = "ABORTED"; } } state.IsDriving = false; state.CurrentOrderId = null; state.NewBaseRequest = true; state.Paused = false; // hủy lệnh thì bỏ luôn trạng thái pause // Xóa action ABORTED sau 2s — đủ để VDA poller (300ms) đọc được vài lần _ = Task.Run(async () => { await Task.Delay(2000); lock (state.ActionStates) state.ActionStates.RemoveAll(a => a.ActionStatus == "ABORTED"); }); return new ApiResult { IsSuccess = true, Message = "Order cancelled" }; } #endregion #region Helpers /// /// AMR specific positions — must match FlowService constants /// AMR_CAP1_X=6.0, AMR_CAP1_Y=0.23 | AMR_CAP2_X=-0.7, AMR_CAP2_Y=-3.19 /// private static readonly Dictionary AmrLocations = new(StringComparer.OrdinalIgnoreCase) { ["Cap1"] = (AMR_CAP1_X, AMR_CAP1_Y), ["Cap2"] = (AMR_CAP2_X, AMR_CAP2_Y), ["Home"] = (0.0, 0.0) }; private static readonly Dictionary ImrLocations = new(StringComparer.OrdinalIgnoreCase) { ["Bt1"] = (IMR_C1_X, IMR_C1_Y), ["BT1"] = (IMR_C1_X, IMR_C1_Y), ["Abb"] = (IMR_ABB_X, IMR_ABB_Y), ["ABB"] = (IMR_ABB_X, IMR_ABB_Y), ["Home"] = (0.0, 0.0), ["HOME"] = (0.0, 0.0) }; private (double X, double Y) GetLocationCoordinates(string locationName, string? robotId = null) { // Try robot-specific locations first if (!string.IsNullOrEmpty(robotId)) { if (robotId.Equals("AMR2WS", StringComparison.OrdinalIgnoreCase) || robotId.StartsWith("AMR", StringComparison.OrdinalIgnoreCase)) { if (AmrLocations.TryGetValue(locationName, out var amrCoords)) return amrCoords; } else if (robotId.Equals("IMR", StringComparison.OrdinalIgnoreCase)) { if (ImrLocations.TryGetValue(locationName, out var imrCoords)) return imrCoords; } } // Try AMR locations (case insensitive) if (AmrLocations.TryGetValue(locationName, out var coords)) return coords; // Try IMR locations (case insensitive) if (ImrLocations.TryGetValue(locationName, out coords)) return coords; // Default to (0, 0) for unknown locations _logger.LogWarning("Unknown location '{Location}' for robot '{RobotId}', defaulting to (0,0)", locationName, robotId); return (0, 0); } private double GetActionParameter(VdaInstantAction action, string key, double defaultValue) { var param = action.ActionParameters?.FirstOrDefault(p => p.Key == key); // VDA5050 dùng dấu chấm thập phân — parse InvariantCulture để khớp với driver, // không phụ thuộc locale máy chạy sim. if (param != null && double.TryParse(param.Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var value)) return value; return defaultValue; } #endregion public void Dispose() { Stop(); _cts?.Dispose(); GC.SuppressFinalize(this); } } #region Mock Models internal class RobotState { public string RobotId { get; set; } = string.Empty; public double X { get; set; } public double Y { get; set; } public double Theta { get; set; } public bool IsOnline { get; set; } public bool NewBaseRequest { get; set; } public bool IsDriving { get; set; } public bool Paused { get; set; } public string? CurrentOrderId { get; set; } public int OrderUpdateId { get; set; } public string? LastNodeId { get; set; } public List ActionStates { get; set; } = new(); } internal class MoveToRequest { public string RobotId { get; set; } = string.Empty; public string RoomName { get; set; } = string.Empty; } internal class InstantActionRequest { public string RobotId { get; set; } = string.Empty; public VdaInstantAction? Action { get; set; } } #endregion