initial commit
This commit is contained in:
338
Lab505.Client/Services/CommandService.cs
Normal file
338
Lab505.Client/Services/CommandService.cs
Normal file
@@ -0,0 +1,338 @@
|
||||
using System.Net.Http.Json;
|
||||
|
||||
namespace Lab505.Client.Services;
|
||||
|
||||
public class CommandService
|
||||
{
|
||||
private readonly HttpClient _http;
|
||||
private readonly ScriptLogService _log;
|
||||
|
||||
public CommandService(HttpClient http, ScriptLogService log)
|
||||
{
|
||||
_http = http;
|
||||
_log = log;
|
||||
}
|
||||
|
||||
// ── IMR ───────────────────────────────────────────────────────────────
|
||||
public Task ImrMoveToAsync(string target, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "MoveTo", isMove: true, $"Target={target}");
|
||||
return PostAsync("/api/imr/vda/move-to", new { Target = target }, ct, "IMR");
|
||||
}
|
||||
|
||||
public Task ImrLoadAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "Load");
|
||||
return PostAsync("/api/imr/vda/load", null, ct, "IMR");
|
||||
}
|
||||
|
||||
public Task ImrUnloadAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "Unload");
|
||||
return PostAsync("/api/imr/vda/unload", null, ct, "IMR");
|
||||
}
|
||||
|
||||
public Task ImrCancelAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "Cancel");
|
||||
return PostAsync("/api/imr/vda/cancel", null, ct, "IMR");
|
||||
}
|
||||
|
||||
public Task ImrPickupAsync(int ok, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "Pickup", @params: $"OK={ok} NG={ng}");
|
||||
return PostAsync("/api/imr/vda/pickup", new { CountOk = ok, CountNg = ng }, ct, "IMR");
|
||||
}
|
||||
|
||||
public Task ImrUndockAsync(double distance, double velocity, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "Undock", isMove: true, $"Dist={distance:F2} Vel={velocity:F2}");
|
||||
return PostAsync("/api/imr/vda/undock", new { Distance = distance, Velocity = velocity }, ct, "IMR");
|
||||
}
|
||||
|
||||
public Task ImrPauseAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "Pause");
|
||||
return PostAsync("/api/imr/vda/pause", null, ct, "IMR");
|
||||
}
|
||||
|
||||
public Task ImrResumeAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "Resume");
|
||||
return PostAsync("/api/imr/vda/resume", null, ct, "IMR");
|
||||
}
|
||||
|
||||
public Task ImrInitPositionAsync(double x, double y, double theta, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "InitPosition", @params: $"X={x:F2} Y={y:F2} θ={theta:F2}");
|
||||
return PostAsync("/api/imr/vda/init-position", new { X = x, Y = y, Theta = theta }, ct, "IMR");
|
||||
}
|
||||
|
||||
public Task ImrResetOpcAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "Reset(OPC)");
|
||||
return PostAsync("/api/imr/opc/reset", null, ct, "IMR");
|
||||
}
|
||||
|
||||
// ── AMR ───────────────────────────────────────────────────────────────
|
||||
public Task AmrMoveToAsync(string target, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("AMR", "MoveTo", isMove: true, $"Target={target}");
|
||||
return PostAsync("/api/amr/vda/move-to", new { Target = target }, ct, "AMR");
|
||||
}
|
||||
|
||||
public Task AmrLoadAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("AMR", "Load");
|
||||
return PostAsync("/api/amr/vda/load", null, ct, "AMR");
|
||||
}
|
||||
|
||||
public Task AmrUnloadAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("AMR", "Unload");
|
||||
return PostAsync("/api/amr/vda/unload", null, ct, "AMR");
|
||||
}
|
||||
|
||||
public Task AmrCancelAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("AMR", "Cancel");
|
||||
return PostAsync("/api/amr/vda/cancel", null, ct, "AMR");
|
||||
}
|
||||
|
||||
public Task AmrUndockAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("AMR", "Undock", isMove: true);
|
||||
return PostAsync("/api/amr/vda/undock", null, ct, "AMR");
|
||||
}
|
||||
|
||||
public Task AmrPauseAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("AMR", "Pause");
|
||||
return PostAsync("/api/amr/vda/pause", null, ct, "AMR");
|
||||
}
|
||||
|
||||
public Task AmrResumeAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("AMR", "Resume");
|
||||
return PostAsync("/api/amr/vda/resume", null, ct, "AMR");
|
||||
}
|
||||
|
||||
public Task AmrInitPositionAsync(double x, double y, double theta, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("AMR", "InitPosition", @params: $"X={x:F2} Y={y:F2} θ={theta:F2}");
|
||||
return PostAsync("/api/amr/vda/init-position", new { X = x, Y = y, Theta = theta }, ct, "AMR");
|
||||
}
|
||||
|
||||
// ── Conveyor ──────────────────────────────────────────────────────────
|
||||
public async Task ConveyorSetCoilAsync(string c, string coil, bool state, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogConveyorSetCoil(c, coil, state);
|
||||
var (ok, err) = await PostConveyorAsync($"/api/conveyor/{c}/{coil}", new { State = state }, ct);
|
||||
_log.LogConveyorWriteResult(c, coil, state, ok, err);
|
||||
}
|
||||
|
||||
// ── Dobot ─────────────────────────────────────────────────────────────
|
||||
public Task DobotPowerOnAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("Dobot", "PowerOn");
|
||||
return PostAsync("/api/dobot/power-on", null, ct, "Dobot");
|
||||
}
|
||||
|
||||
public Task DobotGoHomeAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("Dobot", "GoHome");
|
||||
return PostAsync("/api/dobot/go-home", null, ct, "Dobot");
|
||||
}
|
||||
|
||||
public Task DobotContinueAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("Dobot", "Continue");
|
||||
return PostAsync("/api/dobot/continue", null, ct, "Dobot");
|
||||
}
|
||||
|
||||
public Task DobotCancelAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("Dobot", "Cancel");
|
||||
return PostAsync("/api/dobot/cancel", null, ct, "Dobot");
|
||||
}
|
||||
|
||||
// ── ASRS ──────────────────────────────────────────────────────────────
|
||||
public Task AsrsHomingAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("ASRS", "Homing");
|
||||
return PostAsync("/api/asrs/homing", null, ct, "ASRS");
|
||||
}
|
||||
|
||||
public Task AsrsWorkflowAsync(string op, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("ASRS", $"Workflow", @params: $"op={op}");
|
||||
return PostAsync($"/api/asrs/workflow/{op}", null, ct, "ASRS");
|
||||
}
|
||||
|
||||
// ── Workflow ──────────────────────────────────────────────────────────
|
||||
public Task WorkflowX1AAsync(int times, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "X1A", @params: $"Times={times} NG={ng}");
|
||||
return PostAsync("/api/workflow/x1a", new { Times = times, Ng = ng }, ct, "WF");
|
||||
}
|
||||
|
||||
public Task WorkflowX2AAsync(int times, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "X2A", @params: $"Times={times} NG={ng}");
|
||||
return PostAsync("/api/workflow/x2a", new { Times = times, Ng = ng }, ct, "WF");
|
||||
}
|
||||
|
||||
public Task WorkflowX3AAsync(int times, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "X3A", @params: $"Times={times} NG={ng}");
|
||||
return PostAsync("/api/workflow/x3a", new { Times = times, Ng = ng }, ct, "WF");
|
||||
}
|
||||
|
||||
public Task WorkflowX1BAsync(int times, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "X1B", @params: $"Times={times} NG={ng}");
|
||||
return PostAsync("/api/workflow/x1b", new { Times = times, Ng = ng }, ct, "WF");
|
||||
}
|
||||
|
||||
public Task WorkflowX2BAsync(int times, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "X2B", @params: $"Times={times} NG={ng}");
|
||||
return PostAsync("/api/workflow/x2b", new { Times = times, Ng = ng }, ct, "WF");
|
||||
}
|
||||
|
||||
public Task WorkflowX3BAsync(int times, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "X3B", @params: $"Times={times} NG={ng}");
|
||||
return PostAsync("/api/workflow/x3b", new { Times = times, Ng = ng }, ct, "WF");
|
||||
}
|
||||
|
||||
public Task WorkflowRunCycleAsync(int times, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "RunCycle", @params: $"Times={times} NG={ng}");
|
||||
return PostAsync("/api/workflow/run-cycle", new { Times = times, Ng = ng }, ct, "WF");
|
||||
}
|
||||
|
||||
public Task WorkflowRunStepsAsync(IEnumerable<int> steps, int times, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "RunSteps", @params: $"Steps=[{string.Join(",", steps)}] Times={times} NG={ng}");
|
||||
return PostAsync("/api/workflow/run-steps", new { Steps = steps, Times = times, Ng = ng }, ct, "WF");
|
||||
}
|
||||
|
||||
public Task FlowStepInitAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "Step:Init");
|
||||
return PostAsync("/api/workflow/step/init", null, ct, "WF");
|
||||
}
|
||||
|
||||
public Task FlowStepLoadC2Async(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "Step:LoadC2");
|
||||
return PostAsync("/api/workflow/step/load-c2", null, ct, "WF");
|
||||
}
|
||||
|
||||
public Task FlowStepToCap1Async(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "Step:ToCap1");
|
||||
return PostAsync("/api/workflow/step/to-cap1", null, ct, "WF");
|
||||
}
|
||||
|
||||
public Task FlowStepAmrToImrAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "Step:AmrToImr");
|
||||
return PostAsync("/api/workflow/step/amr-to-imr", null, ct, "WF");
|
||||
}
|
||||
|
||||
public Task FlowStepProcessAsync(int times, int ng, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "Step:Process", @params: $"Times={times} NG={ng}");
|
||||
return PostAsync("/api/workflow/step/process", new { Times = times, Ng = ng }, ct, "WF");
|
||||
}
|
||||
|
||||
public Task FlowStepImrToAmrAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "Step:ImrToAmr");
|
||||
return PostAsync("/api/workflow/step/imr-to-amr", null, ct, "WF");
|
||||
}
|
||||
|
||||
public Task FlowStepToCap2Async(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "Step:ToCap2");
|
||||
return PostAsync("/api/workflow/step/to-cap2", null, ct, "WF");
|
||||
}
|
||||
|
||||
public Task FlowStepUnloadC2Async(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "Step:UnloadC2");
|
||||
return PostAsync("/api/workflow/step/unload-c2", null, ct, "WF");
|
||||
}
|
||||
|
||||
public Task WorkflowHomeRbAsync(CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("WF", "HomeAll");
|
||||
return PostAsync("/api/workflow/home-rb", null, ct, "WF");
|
||||
}
|
||||
|
||||
public Task WorkflowEmergencyStopAsync()
|
||||
{
|
||||
_log.LogCommand("WF", "EMERGENCY STOP");
|
||||
return PostAsync("/api/workflow/emergency-stop", null, default, "WF");
|
||||
}
|
||||
|
||||
// ── Internal ──────────────────────────────────────────────────────────
|
||||
private async Task PostAsync(string url, object? body, CancellationToken ct, string? device = null)
|
||||
{
|
||||
try
|
||||
{
|
||||
var request = new HttpRequestMessage(HttpMethod.Post, url);
|
||||
if (body != null)
|
||||
request.Content = JsonContent.Create(body);
|
||||
var resp = await _http.SendAsync(request, ct);
|
||||
if (!resp.IsSuccessStatusCode && device != null)
|
||||
_log.CancelPending(device, $"HTTP {(int)resp.StatusCode}");
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception ex)
|
||||
{
|
||||
if (device != null) _log.CancelPending(device, ex.Message);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>Conveyor write — trả về (success, errorMessage).</summary>
|
||||
private async Task<(bool ok, string? err)> PostConveyorAsync(string url, object? body, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var request = new HttpRequestMessage(HttpMethod.Post, url);
|
||||
if (body != null)
|
||||
request.Content = JsonContent.Create(body);
|
||||
var resp = await _http.SendAsync(request, ct);
|
||||
var result = await TryReadCommandResultAsync(resp, ct);
|
||||
|
||||
if (resp.IsSuccessStatusCode)
|
||||
return result is { Success: false }
|
||||
? (false, result.Error ?? "Modbus write failed")
|
||||
: (true, null);
|
||||
|
||||
return (false, result?.Error ?? $"HTTP {(int)resp.StatusCode}");
|
||||
}
|
||||
catch (OperationCanceledException) { throw; }
|
||||
catch (Exception ex) { return (false, ex.Message); }
|
||||
}
|
||||
|
||||
private static async Task<ApiCommandResult?> TryReadCommandResultAsync(HttpResponseMessage resp, CancellationToken ct)
|
||||
{
|
||||
if (resp.Content is null)
|
||||
return null;
|
||||
|
||||
try
|
||||
{
|
||||
return await resp.Content.ReadFromJsonAsync<ApiCommandResult>(cancellationToken: ct);
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private sealed record ApiCommandResult(bool Success, string? Error);
|
||||
}
|
||||
151
Lab505.Client/Services/ImrInitialPoseService.cs
Normal file
151
Lab505.Client/Services/ImrInitialPoseService.cs
Normal file
@@ -0,0 +1,151 @@
|
||||
using System.Net.Http.Json;
|
||||
|
||||
namespace Lab505.Client.Services;
|
||||
|
||||
public sealed class ImrInitialPoseService
|
||||
{
|
||||
private const int OperationPollAttempts = 15;
|
||||
private const int PositionPollAttempts = 20;
|
||||
private const int PollDelayMs = 300;
|
||||
private const double PositionTolerance = 0.1;
|
||||
|
||||
private readonly HttpClient _http;
|
||||
private readonly ScriptLogService _log;
|
||||
|
||||
public ImrInitialPoseService(HttpClient http, ScriptLogService log)
|
||||
{
|
||||
_http = http;
|
||||
_log = log;
|
||||
}
|
||||
|
||||
public async Task<ImrInitialPoseResult> RunAsync(double x, double y, double yaw, CancellationToken ct = default)
|
||||
{
|
||||
_log.LogCommand("IMR", "InitPose(OPC)", isMove: true, $"x={x:F2} y={y:F2} yaw={yaw:F2}");
|
||||
|
||||
var operationId = await StartAsync(x, y, yaw, ct);
|
||||
if (operationId is null)
|
||||
return new(ImrInitialPoseOutcome.SendFailed);
|
||||
|
||||
var operation = await WaitForOperationAsync(operationId, ct);
|
||||
if (operation.Status == "Failed")
|
||||
return new(ImrInitialPoseOutcome.OperationFailed, operation.Error);
|
||||
|
||||
var position = await WaitForPositionAsync(x, y, ct);
|
||||
return position.IsMatched
|
||||
? new(ImrInitialPoseOutcome.Success, ActualX: position.ActualX, ActualY: position.ActualY)
|
||||
: new(ImrInitialPoseOutcome.PositionMismatch,
|
||||
ActualX: position.ActualX,
|
||||
ActualY: position.ActualY,
|
||||
WaitSeconds: PositionPollAttempts * PollDelayMs / 1000);
|
||||
}
|
||||
|
||||
private async Task<string?> StartAsync(double x, double y, double yaw, CancellationToken ct)
|
||||
{
|
||||
try
|
||||
{
|
||||
var response = await _http.PostAsJsonAsync("/api/imr/opc/init-pose", new { X = x, Y = y, Yaw = yaw }, ct);
|
||||
if (!response.IsSuccessStatusCode)
|
||||
return null;
|
||||
|
||||
var body = await response.Content.ReadFromJsonAsync<OperationAcceptedDto>(cancellationToken: ct);
|
||||
return body?.OperationId;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<OperationStatusDto> WaitForOperationAsync(string operationId, CancellationToken ct)
|
||||
{
|
||||
for (var i = 0; i < OperationPollAttempts; i++)
|
||||
{
|
||||
await Task.Delay(PollDelayMs, ct);
|
||||
|
||||
try
|
||||
{
|
||||
var operation = await _http.GetFromJsonAsync<OperationStatusDto>($"/api/operations/{operationId}", ct);
|
||||
if (operation?.Status is "Completed" or "Failed")
|
||||
return operation;
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
return new(operationId, "Completed", null);
|
||||
}
|
||||
|
||||
private async Task<PositionCheckResult> WaitForPositionAsync(double expectedX, double expectedY, CancellationToken ct)
|
||||
{
|
||||
double? actualX = null;
|
||||
double? actualY = null;
|
||||
|
||||
for (var i = 0; i < PositionPollAttempts; i++)
|
||||
{
|
||||
await Task.Delay(PollDelayMs, ct);
|
||||
|
||||
try
|
||||
{
|
||||
var status = await _http.GetFromJsonAsync<ImrStatusDto>("/api/imr/status", ct);
|
||||
if (status is null)
|
||||
continue;
|
||||
|
||||
actualX = status.X_Opc;
|
||||
actualY = status.Y_Opc;
|
||||
|
||||
if (Math.Abs(status.X_Opc - expectedX) <= PositionTolerance &&
|
||||
Math.Abs(status.Y_Opc - expectedY) <= PositionTolerance)
|
||||
return new(true, actualX, actualY);
|
||||
}
|
||||
catch (OperationCanceledException)
|
||||
{
|
||||
throw;
|
||||
}
|
||||
catch
|
||||
{
|
||||
}
|
||||
}
|
||||
|
||||
return new(false, actualX, actualY);
|
||||
}
|
||||
|
||||
private sealed record OperationAcceptedDto(string OperationId);
|
||||
private sealed record OperationStatusDto(string Id, string Status, string? Error);
|
||||
private sealed record ImrStatusDto(
|
||||
double X_Opc,
|
||||
double Y_Opc,
|
||||
double Theta_Opc,
|
||||
string NavStatus,
|
||||
string DobotStatus,
|
||||
string ConveyorStatus,
|
||||
double X_Vda,
|
||||
double Y_Vda,
|
||||
bool IsOnline,
|
||||
string[] Errors);
|
||||
|
||||
private sealed record PositionCheckResult(bool IsMatched, double? ActualX, double? ActualY);
|
||||
}
|
||||
|
||||
public enum ImrInitialPoseOutcome
|
||||
{
|
||||
Success,
|
||||
SendFailed,
|
||||
OperationFailed,
|
||||
PositionMismatch
|
||||
}
|
||||
|
||||
public sealed record ImrInitialPoseResult(
|
||||
ImrInitialPoseOutcome Outcome,
|
||||
string? Error = null,
|
||||
double? ActualX = null,
|
||||
double? ActualY = null,
|
||||
int WaitSeconds = 0);
|
||||
38
Lab505.Client/Services/LangService.cs
Normal file
38
Lab505.Client/Services/LangService.cs
Normal file
@@ -0,0 +1,38 @@
|
||||
using System.Net.Http.Json;
|
||||
|
||||
namespace Lab505.Client.Services;
|
||||
|
||||
public class LangService
|
||||
{
|
||||
public string Current { get; private set; } = "vi";
|
||||
|
||||
public event Action? LangChanged;
|
||||
|
||||
public string T(string vi, string en) => Current == "en" ? en : vi;
|
||||
|
||||
public void Set(string lang)
|
||||
{
|
||||
if (Current == lang) return;
|
||||
Current = lang;
|
||||
LangChanged?.Invoke();
|
||||
}
|
||||
|
||||
public async Task LoadAsync(HttpClient http)
|
||||
{
|
||||
try
|
||||
{
|
||||
var prefs = await http.GetFromJsonAsync<PrefsDto>("/api/prefs");
|
||||
if (prefs?.Lang is { } l) Set(l);
|
||||
}
|
||||
catch { }
|
||||
}
|
||||
|
||||
public async Task ToggleAsync(HttpClient http)
|
||||
{
|
||||
Set(Current == "vi" ? "en" : "vi");
|
||||
try { await http.PutAsJsonAsync("/api/prefs", new { Lang = (string?)Current, NotifMuted = (bool?)null }); }
|
||||
catch { }
|
||||
}
|
||||
|
||||
private record PrefsDto(string? Lang);
|
||||
}
|
||||
68
Lab505.Client/Services/LogFormat.cs
Normal file
68
Lab505.Client/Services/LogFormat.cs
Normal file
@@ -0,0 +1,68 @@
|
||||
namespace Lab505.Client.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Single source of truth for output-log HTML rendering.
|
||||
/// Badges: INFO · DONE · ERR · WARN · DEV
|
||||
/// Columns: [ts]=75px BADGE=46px DEVICE=54px COMMAND=220px STATUS=flexible
|
||||
/// </summary>
|
||||
public static class LogFormat
|
||||
{
|
||||
// ── Severity colors (MudBlazor-aligned) ──────────────────────────────
|
||||
public const string CInfo = "#42a5f5"; // INFO blue
|
||||
public const string CWarn = "#ffa726"; // WARN orange
|
||||
public const string CSuccess = "#66bb6a"; // DONE green
|
||||
public const string CError = "#ef5350"; // ERR red
|
||||
public const string CDev = "#9575cd"; // DEV purple
|
||||
|
||||
// ── Column styles ─────────────────────────────────────────────────────
|
||||
public const string ColTs = "display:inline-block;width:75px;color:#484848";
|
||||
public const string ColDev = "display:inline-block;width:54px;color:#9e9e9e";
|
||||
public const string ColCmd = "display:inline-block;width:350px;color:#c8c8c8";
|
||||
|
||||
public static string Ts() => DateTime.Now.ToString("HH:mm:ss");
|
||||
|
||||
// ── Level → (color, badge) ────────────────────────────────────────────
|
||||
public static (string color, string badge) LevelBadge(string level) => level switch
|
||||
{
|
||||
"success" => (CSuccess, "DONE"),
|
||||
"error" => (CError, "ERR"),
|
||||
"warning" => (CWarn, "WARN"),
|
||||
"dev" => (CDev, "DEV"),
|
||||
"heartbeat" => (CInfo, "HB"),
|
||||
_ => (CInfo, "INFO"),
|
||||
};
|
||||
|
||||
// ── Level → status HTML ───────────────────────────────────────────────
|
||||
public static string LevelStatus(string level) => level switch
|
||||
{
|
||||
"success" => $"<span style='color:{CSuccess}'>✓</span>",
|
||||
"error" => $"<span style='color:{CError}'>✗</span>",
|
||||
"warning" => $"<span style='color:{CWarn}'>⚠</span>",
|
||||
_ => "",
|
||||
};
|
||||
|
||||
/// <summary>5-column line: [ts] BADGE DEVICE COMMAND STATUS │ detail</summary>
|
||||
public static string Line(string color, string badge, string device, string command, string status, string? detail = null)
|
||||
{
|
||||
var badgeStyle = $"display:inline-block;width:46px;color:{color};font-weight:700";
|
||||
var detPart = detail != null
|
||||
? $"<span style='color:#606060'> │ </span><span style='color:#a0a0a0'>{detail}</span>"
|
||||
: "";
|
||||
return $"<span style='{ColTs}'>[{Ts()}]</span>" +
|
||||
$"<span style='{badgeStyle}'>{badge}</span>" +
|
||||
$"<span style='{ColDev}'>{device}</span>" +
|
||||
$"<span style='{ColCmd}'>{command}</span>" +
|
||||
$"<span style='color:#c8c8c8'>{status}</span>" +
|
||||
detPart;
|
||||
}
|
||||
|
||||
/// <summary>3-column line for DEV state changes: [ts] BADGE DEVICE message</summary>
|
||||
public static string LineRaw(string color, string badge, string device, string msg)
|
||||
{
|
||||
var badgeStyle = $"display:inline-block;width:46px;color:{color};font-weight:700";
|
||||
return $"<span style='{ColTs}'>[{Ts()}]</span>" +
|
||||
$"<span style='{badgeStyle}'>{badge}</span>" +
|
||||
$"<span style='{ColDev}'>{device}</span>" +
|
||||
$"<span style='color:#c8c8c8'>{msg}</span>";
|
||||
}
|
||||
}
|
||||
794
Lab505.Client/Services/ScriptLogService.cs
Normal file
794
Lab505.Client/Services/ScriptLogService.cs
Normal file
@@ -0,0 +1,794 @@
|
||||
using Lab505.Shared;
|
||||
|
||||
namespace Lab505.Client.Services;
|
||||
|
||||
/// <summary>
|
||||
/// Singleton (per WASM session) log bus.
|
||||
/// Mỗi lệnh sinh ra tối đa 3 dòng:
|
||||
/// 1. → gửi (ngay khi CommandService gọi LogCommand)
|
||||
/// 2. ✓ robot nhận (khi NBR đổi sang true hoặc busy bắt đầu)
|
||||
/// 3. ✓ hoàn thành / ✗ lỗi (khi busy trở về false hoặc action FINISHED/FAILED)
|
||||
/// </summary>
|
||||
public class ScriptLogService : IDisposable
|
||||
{
|
||||
private readonly StateService _state;
|
||||
private readonly LangService _lang;
|
||||
private readonly List<string> _lines = new();
|
||||
private readonly System.Timers.Timer _timeoutTimer;
|
||||
private const int TimeoutSeconds = 1200; // 20 phút
|
||||
|
||||
// Aliases → LogFormat (single source of truth)
|
||||
private const string CInfo = LogFormat.CInfo;
|
||||
private const string CWarn = LogFormat.CWarn;
|
||||
private const string CSuccess = LogFormat.CSuccess;
|
||||
private const string CError = LogFormat.CError;
|
||||
private const string CDev = LogFormat.CDev;
|
||||
|
||||
public IReadOnlyList<string> Lines => _lines;
|
||||
public event Action? LogChanged;
|
||||
|
||||
public void Clear()
|
||||
{
|
||||
_lines.Clear();
|
||||
LogChanged?.Invoke();
|
||||
}
|
||||
|
||||
// ── Pending command per device ────────────────────────────────────────
|
||||
private PendingCmd? _imrPending;
|
||||
private PendingCmd? _amrPending;
|
||||
private PendingCmd? _dobotPending;
|
||||
private PendingCmd? _asrsPending;
|
||||
private PendingCmd? _wfPending;
|
||||
private PendingConveyorCmd? _conveyorPending;
|
||||
private bool? _conveyorTargetPrev;
|
||||
// Last command sent per robot (for NBR context after pending clears)
|
||||
private string? _lastImrCmd;
|
||||
private string? _lastAmrCmd;
|
||||
|
||||
// ── Previous state snapshots (for delta detection) ────────────────────
|
||||
private bool? _prevImrNBR;
|
||||
private bool? _prevAmrNBR;
|
||||
private bool _prevImrBusy;
|
||||
private bool _prevAmrBusy;
|
||||
private bool _prevDobotBusy;
|
||||
private bool _prevAsrsBusy;
|
||||
private bool _prevWfRunning;
|
||||
private string? _prevImrErr;
|
||||
private string? _prevAmrErr;
|
||||
private string? _prevDobotErr;
|
||||
private string? _prevAsrsErr;
|
||||
private string? _prevWfErr;
|
||||
private string? _prevImrActionId;
|
||||
private string? _prevImrActionStatus;
|
||||
private string? _prevAmrActionId;
|
||||
private string? _prevAmrActionStatus;
|
||||
private string? _prevConveyorWriteError;
|
||||
|
||||
// ── Dev mode ──────────────────────────────────────────────────────────
|
||||
public bool IsDevMode { get; set; }
|
||||
|
||||
private bool? _devImrNBR, _devAmrNBR;
|
||||
private bool _devImrOnline, _devAmrOnline;
|
||||
private string? _devImrActId, _devImrActStatus;
|
||||
private string? _devAmrActId, _devAmrActStatus;
|
||||
private bool _devImrBusy, _devAmrBusy, _devDobotBusy, _devAsrsBusy;
|
||||
private bool _devWfRunning;
|
||||
private bool? _devAsrsSafety, _devAsrsOffline;
|
||||
// Conveyor coils
|
||||
private bool? _devC1In, _devC1Out, _devC1IMRin, _devC1IMRout;
|
||||
private bool? _devC1HasGoods, _devC1NotGoods, _devC1Ready;
|
||||
private bool? _devC2In, _devC2Out, _devC2HasGoods, _devC2NotGoods, _devC2Ready;
|
||||
// ASRS slots
|
||||
private bool? _devX11, _devX12, _devX13;
|
||||
private bool? _devX21, _devX22, _devX23;
|
||||
private bool? _devX31, _devX32, _devX33;
|
||||
private bool? _devX41, _devX42, _devX43;
|
||||
|
||||
public ScriptLogService(StateService state, LangService lang)
|
||||
{
|
||||
_state = state;
|
||||
_lang = lang;
|
||||
state.ImrChanged += OnImrChanged;
|
||||
state.AmrChanged += OnAmrChanged;
|
||||
state.WorkflowChanged += OnWorkflowChanged;
|
||||
state.AsrsChanged += OnAsrsChanged;
|
||||
state.ConveyorChanged += OnConveyorChanged;
|
||||
|
||||
// snapshot initial state
|
||||
_prevImrNBR = state.Imr.NewBaseRequest;
|
||||
_prevAmrNBR = state.Amr.NewBaseRequest;
|
||||
_prevImrBusy = state.Workflow.ImrBusy;
|
||||
_prevAmrBusy = state.Workflow.AmrBusy;
|
||||
_prevDobotBusy = state.Workflow.DobotBusy;
|
||||
_prevAsrsBusy = state.Asrs.IsBusy;
|
||||
_prevWfRunning = state.Workflow.IsRunning;
|
||||
_prevImrErr = state.Workflow.ImrExecError;
|
||||
_prevAmrErr = state.Workflow.AmrExecError;
|
||||
_prevDobotErr = state.Workflow.DobotExecError;
|
||||
_prevAsrsErr = state.Asrs.LastError;
|
||||
_prevWfErr = state.Workflow.LastError;
|
||||
_prevConveyorWriteError = state.Conveyor.WriteError;
|
||||
|
||||
// Dev snapshots
|
||||
var _di = state.Imr; var _da = state.Amr; var _dw = state.Workflow;
|
||||
var _ds = state.Asrs; var _dc = state.Conveyor;
|
||||
_devImrNBR = _di.NewBaseRequest; _devAmrNBR = _da.NewBaseRequest;
|
||||
_devImrOnline = _di.IsOnline; _devAmrOnline = _da.IsOnline;
|
||||
_devImrActId = _di.Actions.Length > 0 ? _di.Actions[0].ActionID : null;
|
||||
_devImrActStatus = _di.Actions.Length > 0 ? _di.Actions[0].ActionStatus : null;
|
||||
_devAmrActId = _da.Actions.Length > 0 ? _da.Actions[0].ActionID : null;
|
||||
_devAmrActStatus = _da.Actions.Length > 0 ? _da.Actions[0].ActionStatus : null;
|
||||
_devImrBusy = _dw.ImrBusy; _devAmrBusy = _dw.AmrBusy; _devDobotBusy = _dw.DobotBusy;
|
||||
_devAsrsBusy = _ds.IsBusy; _devWfRunning = _dw.IsRunning;
|
||||
_devAsrsSafety = _ds.SAFETY_MODE; _devAsrsOffline = _ds.IsOffline;
|
||||
_devC1In = _dc.C1In; _devC1Out = _dc.C1Out; _devC1IMRin = _dc.C1IMRin; _devC1IMRout = _dc.C1IMRout;
|
||||
_devC1HasGoods = _dc.C1HasGoods; _devC1NotGoods = _dc.C1NotGoods; _devC1Ready = _dc.C1Ready;
|
||||
_devC2In = _dc.C2In; _devC2Out = _dc.C2Out;
|
||||
_devC2HasGoods = _dc.C2HasGoods; _devC2NotGoods = _dc.C2NotGoods; _devC2Ready = _dc.C2Ready;
|
||||
_devX11 = _ds.X11; _devX12 = _ds.X12; _devX13 = _ds.X13;
|
||||
_devX21 = _ds.X21; _devX22 = _ds.X22; _devX23 = _ds.X23;
|
||||
_devX31 = _ds.X31; _devX32 = _ds.X32; _devX33 = _ds.X33;
|
||||
_devX41 = _ds.X41; _devX42 = _ds.X42; _devX43 = _ds.X43;
|
||||
|
||||
_timeoutTimer = new System.Timers.Timer(15_000);
|
||||
_timeoutTimer.Elapsed += (_, _) => CheckTimeouts();
|
||||
_timeoutTimer.AutoReset = true;
|
||||
_timeoutTimer.Start();
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
_timeoutTimer.Dispose();
|
||||
}
|
||||
|
||||
// ── Timeout check ─────────────────────────────────────────────────────
|
||||
private void CheckTimeouts()
|
||||
{
|
||||
var now = DateTime.Now;
|
||||
if (_imrPending != null && (now - _imrPending.SentAt).TotalSeconds > TimeoutSeconds)
|
||||
CancelPending("IMR", _lang.T("⏱ không phản hồi", "⏱ no response"));
|
||||
if (_amrPending != null && (now - _amrPending.SentAt).TotalSeconds > TimeoutSeconds)
|
||||
CancelPending("AMR", _lang.T("⏱ không phản hồi", "⏱ no response"));
|
||||
if (_dobotPending != null && (now - _dobotPending.SentAt).TotalSeconds > TimeoutSeconds)
|
||||
CancelPending("Dobot", _lang.T("⏱ không phản hồi", "⏱ no response"));
|
||||
if (_asrsPending != null && (now - _asrsPending.SentAt).TotalSeconds > TimeoutSeconds)
|
||||
CancelPending("ASRS", _lang.T("⏱ không phản hồi", "⏱ no response"));
|
||||
if (_wfPending != null && (now - _wfPending.SentAt).TotalSeconds > TimeoutSeconds)
|
||||
CancelPending("WF", _lang.T("⏱ không phản hồi", "⏱ no response"));
|
||||
}
|
||||
|
||||
// ── Cancel pending (HTTP error hoặc timeout) ──────────────────────────
|
||||
public void CancelPending(string device, string reason)
|
||||
{
|
||||
PendingCmd? p = device switch
|
||||
{
|
||||
"IMR" => _imrPending,
|
||||
"AMR" => _amrPending,
|
||||
"Dobot" => _dobotPending,
|
||||
"ASRS" => _asrsPending,
|
||||
"WF" => _wfPending,
|
||||
_ => null
|
||||
};
|
||||
if (p == null) return;
|
||||
|
||||
Push(Line(CError, "ERR", device, p.Command, _lang.T("✗ lỗi", "✗ error"), reason));
|
||||
|
||||
switch (device)
|
||||
{
|
||||
case "IMR": _imrPending = null; break;
|
||||
case "AMR": _amrPending = null; break;
|
||||
case "Dobot": _dobotPending = null; break;
|
||||
case "ASRS": _asrsPending = null; break;
|
||||
case "WF": _wfPending = null; break;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Raw line (script hub hoặc caller khác) ────────────────────────────
|
||||
public void Log(string htmlLine)
|
||||
{
|
||||
_lines.Insert(0, htmlLine);
|
||||
Trim();
|
||||
LogChanged?.Invoke();
|
||||
}
|
||||
|
||||
public void LogNotification(NotificationDto notification)
|
||||
{
|
||||
var (color, badge) = LogFormat.LevelBadge(notification.Level);
|
||||
var status = LogFormat.LevelStatus(notification.Level);
|
||||
var source = string.IsNullOrWhiteSpace(notification.Source)
|
||||
? TryExtractSource(notification.Message)
|
||||
: notification.Source;
|
||||
var device = MapNotificationDevice(source);
|
||||
var command = string.IsNullOrWhiteSpace(notification.Command)
|
||||
? notification.Message
|
||||
: notification.Command!;
|
||||
var detail = notification.Detail;
|
||||
|
||||
Log(Line(color, badge, device, command, status, detail));
|
||||
|
||||
if (IsDevMode && ShouldCaptureSystemSnapshot(notification, source))
|
||||
LogSystemSnapshot($"{device}:{command}");
|
||||
}
|
||||
|
||||
// ── Ghi lệnh vừa gửi ─────────────────────────────────────────────────
|
||||
public void LogCommand(string device, string command, bool isMove = false, string? @params = null)
|
||||
{
|
||||
Push(Line(CInfo, "INFO", device, command, _lang.T("→ gửi", "→ sent"), @params));
|
||||
|
||||
var wf = _state.Workflow;
|
||||
var imr = _state.Imr;
|
||||
var amr = _state.Amr;
|
||||
|
||||
switch (device)
|
||||
{
|
||||
case "IMR":
|
||||
_lastImrCmd = command;
|
||||
_imrPending = new(command, @params, isMove, DateTime.Now);
|
||||
_prevImrNBR = imr.NewBaseRequest;
|
||||
_prevImrErr = wf.ImrExecError;
|
||||
_prevImrActionId = imr.Actions.Length > 0 ? imr.Actions[0].ActionID : null;
|
||||
_prevImrActionStatus = imr.Actions.Length > 0 ? imr.Actions[0].ActionStatus : null;
|
||||
break;
|
||||
|
||||
case "AMR":
|
||||
_lastAmrCmd = command;
|
||||
_amrPending = new(command, @params, isMove, DateTime.Now);
|
||||
_prevAmrNBR = amr.NewBaseRequest;
|
||||
_prevAmrErr = wf.AmrExecError;
|
||||
_prevAmrActionId = amr.Actions.Length > 0 ? amr.Actions[0].ActionID : null;
|
||||
_prevAmrActionStatus = amr.Actions.Length > 0 ? amr.Actions[0].ActionStatus : null;
|
||||
break;
|
||||
|
||||
case "Dobot":
|
||||
_dobotPending = new(command, @params, false, DateTime.Now);
|
||||
_prevDobotErr = wf.DobotExecError;
|
||||
break;
|
||||
|
||||
case "ASRS":
|
||||
_asrsPending = new(command, @params, false, DateTime.Now);
|
||||
_prevAsrsErr = _state.Asrs.LastError;
|
||||
break;
|
||||
|
||||
case "WF":
|
||||
if (command != "EMERGENCY STOP" && !IsXCycleCommand(command))
|
||||
{
|
||||
_wfPending = new(command, @params, false, DateTime.Now);
|
||||
_prevWfErr = wf.LastError;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
public void LogConveyorSetCoil(string c, string coil, bool expectedValue)
|
||||
{
|
||||
var key = c + coil;
|
||||
Push(Line(CInfo, "INFO", "CV", "SetCoil", _lang.T("→ gửi", "→ sent"), $"{key}={expectedValue}"));
|
||||
_conveyorPending = new(key, expectedValue);
|
||||
_conveyorTargetPrev = GetCoil(_state.Conveyor, key);
|
||||
_prevConveyorWriteError = _state.Conveyor.WriteError;
|
||||
}
|
||||
|
||||
public void LogConveyorWriteResult(string c, string coil, bool expectedValue, bool ok, string? error)
|
||||
{
|
||||
var key = c + coil;
|
||||
if (ok)
|
||||
Push(Line(CSuccess, "DONE", "CV", "SetCoil", _lang.T("✓ PLC write OK", "✓ PLC write OK"), $"{key}={expectedValue}"));
|
||||
else
|
||||
Push(Line(CError, "ERR", "CV", "SetCoil", _lang.T("✗ write error", "✗ write error"), $"{key}={expectedValue} | {error}"));
|
||||
|
||||
if (!ok) _conveyorPending = null;
|
||||
}
|
||||
|
||||
// ── State handlers ────────────────────────────────────────────────────
|
||||
|
||||
private void OnImrChanged()
|
||||
{
|
||||
var imr = _state.Imr;
|
||||
|
||||
if (_imrPending != null)
|
||||
{
|
||||
if (imr.NewBaseRequest == true && _prevImrNBR != true)
|
||||
Push(Line(CWarn, "WARN", "IMR", _imrPending.Command, "✓ New Base Request"));
|
||||
|
||||
if (imr.Actions.Length > 0)
|
||||
{
|
||||
var a = imr.Actions[0];
|
||||
if (a.ActionID != _prevImrActionId || a.ActionStatus != _prevImrActionStatus)
|
||||
{
|
||||
var statusStr = a.ActionStatus ?? "?";
|
||||
if (statusStr is "RUNNING" or "INITIALIZING")
|
||||
Push(Line(CWarn, "WARN", "IMR", _imrPending.Command, $"action {a.ActionID}", statusStr));
|
||||
else if (statusStr == "FINISHED")
|
||||
Push(Line(CSuccess, "DONE", "IMR", _imrPending.Command, $"action {a.ActionID}", _lang.T("hoàn thành", "done")));
|
||||
else if (statusStr is "FAILED" or "FAILED_FATAL")
|
||||
Push(Line(CError, "ERR", "IMR", _imrPending.Command, $"action {a.ActionID}", _lang.T("thất bại", "failed")));
|
||||
|
||||
_prevImrActionId = a.ActionID;
|
||||
_prevImrActionStatus = a.ActionStatus;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_prevImrNBR = imr.NewBaseRequest;
|
||||
|
||||
if (IsDevMode)
|
||||
{
|
||||
bool noPending = _imrPending == null;
|
||||
if (imr.IsOnline != _devImrOnline)
|
||||
{ DevPush("IMR", $"online={imr.IsOnline}"); _devImrOnline = imr.IsOnline; }
|
||||
if (imr.NewBaseRequest != _devImrNBR)
|
||||
{
|
||||
if (noPending)
|
||||
DevPush("IMR", _lastImrCmd ?? "", $"New Base Request={imr.NewBaseRequest}");
|
||||
_devImrNBR = imr.NewBaseRequest;
|
||||
}
|
||||
if (imr.Actions.Length > 0)
|
||||
{
|
||||
var a = imr.Actions[0];
|
||||
if (a.ActionID != _devImrActId || a.ActionStatus != _devImrActStatus)
|
||||
{ if (noPending) DevPush("IMR", a.ActionID ?? "", a.ActionStatus ?? "?"); _devImrActId = a.ActionID; _devImrActStatus = a.ActionStatus; }
|
||||
}
|
||||
else if (_devImrActId != null)
|
||||
{ if (noPending) DevPush("IMR", "actions cleared"); _devImrActId = null; _devImrActStatus = null; }
|
||||
}
|
||||
}
|
||||
|
||||
private void OnAmrChanged()
|
||||
{
|
||||
var amr = _state.Amr;
|
||||
|
||||
if (_amrPending != null)
|
||||
{
|
||||
if (amr.NewBaseRequest == true && _prevAmrNBR != true)
|
||||
Push(Line(CWarn, "WARN", "AMR", _amrPending.Command, "✓ New Base Request"));
|
||||
|
||||
if (amr.Actions.Length > 0)
|
||||
{
|
||||
var a = amr.Actions[0];
|
||||
if (a.ActionID != _prevAmrActionId || a.ActionStatus != _prevAmrActionStatus)
|
||||
{
|
||||
var statusStr = a.ActionStatus ?? "?";
|
||||
if (statusStr is "RUNNING" or "INITIALIZING")
|
||||
Push(Line(CWarn, "WARN", "AMR", _amrPending.Command, $"action {a.ActionID}", statusStr));
|
||||
else if (statusStr == "FINISHED")
|
||||
Push(Line(CSuccess, "DONE", "AMR", _amrPending.Command, $"action {a.ActionID}", _lang.T("hoàn thành", "done")));
|
||||
else if (statusStr is "FAILED" or "FAILED_FATAL")
|
||||
Push(Line(CError, "ERR", "AMR", _amrPending.Command, $"action {a.ActionID}", _lang.T("thất bại", "failed")));
|
||||
|
||||
_prevAmrActionId = a.ActionID;
|
||||
_prevAmrActionStatus = a.ActionStatus;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
_prevAmrNBR = amr.NewBaseRequest;
|
||||
|
||||
if (IsDevMode)
|
||||
{
|
||||
bool noPending = _amrPending == null;
|
||||
if (amr.IsOnline != _devAmrOnline)
|
||||
{ DevPush("AMR", $"online={amr.IsOnline}"); _devAmrOnline = amr.IsOnline; }
|
||||
if (amr.NewBaseRequest != _devAmrNBR)
|
||||
{
|
||||
if (noPending)
|
||||
DevPush("AMR", _lastAmrCmd ?? "", $"New Base Request={amr.NewBaseRequest}");
|
||||
_devAmrNBR = amr.NewBaseRequest;
|
||||
}
|
||||
if (amr.Actions.Length > 0)
|
||||
{
|
||||
var a = amr.Actions[0];
|
||||
if (a.ActionID != _devAmrActId || a.ActionStatus != _devAmrActStatus)
|
||||
{ if (noPending) DevPush("AMR", a.ActionID ?? "", a.ActionStatus ?? "?"); _devAmrActId = a.ActionID; _devAmrActStatus = a.ActionStatus; }
|
||||
}
|
||||
else if (_devAmrActId != null)
|
||||
{ if (noPending) DevPush("AMR", "actions cleared"); _devAmrActId = null; _devAmrActStatus = null; }
|
||||
}
|
||||
}
|
||||
|
||||
private void OnWorkflowChanged()
|
||||
{
|
||||
var wf = _state.Workflow;
|
||||
|
||||
// ── IMR busy ──────────────────────────────────────────────────────
|
||||
if (_imrPending != null)
|
||||
{
|
||||
if (!_prevImrBusy && wf.ImrBusy)
|
||||
{
|
||||
var fromPos = _imrPending.IsMove ? $"from x={_state.Imr.X:F2} y={_state.Imr.Y:F2}" : null;
|
||||
Push(Line(CWarn, "WARN", "IMR", _imrPending.Command, _lang.T("đang thực hiện", "executing"), fromPos));
|
||||
}
|
||||
else if (_prevImrBusy && !wf.ImrBusy)
|
||||
{
|
||||
var newErr = wf.ImrExecError != null && wf.ImrExecError != _prevImrErr ? wf.ImrExecError : null;
|
||||
if (newErr != null)
|
||||
Push(Line(CError, "ERR", "IMR", _imrPending.Command, newErr));
|
||||
else
|
||||
{
|
||||
var elapsed = $"{(DateTime.Now - _imrPending.SentAt).TotalSeconds:F1}s";
|
||||
var pos = _imrPending.IsMove ? $"x={_state.Imr.X:F2} y={_state.Imr.Y:F2}" : null;
|
||||
var detail = pos != null ? $"{elapsed} │ {pos}" : elapsed;
|
||||
Push(Line(CSuccess, "DONE", "IMR", _imrPending.Command, _lang.T("hoàn thành", "done"), detail));
|
||||
}
|
||||
_imrPending = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── AMR busy ──────────────────────────────────────────────────────
|
||||
if (_amrPending != null)
|
||||
{
|
||||
if (!_prevAmrBusy && wf.AmrBusy)
|
||||
{
|
||||
var fromPos = _amrPending.IsMove ? $"from x={_state.Amr.X:F2} y={_state.Amr.Y:F2}" : null;
|
||||
Push(Line(CWarn, "WARN", "AMR", _amrPending.Command, _lang.T("đang thực hiện", "executing"), fromPos));
|
||||
}
|
||||
else if (_prevAmrBusy && !wf.AmrBusy)
|
||||
{
|
||||
var newErr = wf.AmrExecError != null && wf.AmrExecError != _prevAmrErr ? wf.AmrExecError : null;
|
||||
if (newErr != null)
|
||||
Push(Line(CError, "ERR", "AMR", _amrPending.Command, newErr));
|
||||
else
|
||||
{
|
||||
var elapsed = $"{(DateTime.Now - _amrPending.SentAt).TotalSeconds:F1}s";
|
||||
var pos = _amrPending.IsMove ? $"x={_state.Amr.X:F2} y={_state.Amr.Y:F2}" : null;
|
||||
var detail = pos != null ? $"{elapsed} │ {pos}" : elapsed;
|
||||
Push(Line(CSuccess, "DONE", "AMR", _amrPending.Command, _lang.T("hoàn thành", "done"), detail));
|
||||
}
|
||||
_amrPending = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Dobot busy ────────────────────────────────────────────────────
|
||||
if (_dobotPending != null)
|
||||
{
|
||||
if (!_prevDobotBusy && wf.DobotBusy)
|
||||
{
|
||||
Push(Line(CWarn, "WARN", "Dobot", _dobotPending.Command, _lang.T("đang thực hiện", "executing")));
|
||||
}
|
||||
else if (_prevDobotBusy && !wf.DobotBusy)
|
||||
{
|
||||
var newErr = wf.DobotExecError != null && wf.DobotExecError != _prevDobotErr ? wf.DobotExecError : null;
|
||||
if (newErr != null)
|
||||
Push(Line(CError, "ERR", "Dobot", _dobotPending.Command, newErr));
|
||||
else
|
||||
{
|
||||
var elapsed = $"{(DateTime.Now - _dobotPending.SentAt).TotalSeconds:F1}s";
|
||||
Push(Line(CSuccess, "DONE", "Dobot", _dobotPending.Command, _lang.T("hoàn thành", "done"), elapsed));
|
||||
}
|
||||
_dobotPending = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Workflow cycle ────────────────────────────────────────────────
|
||||
if (_wfPending != null)
|
||||
{
|
||||
if (!_prevWfRunning && wf.IsRunning)
|
||||
{
|
||||
Push(Line(CWarn, "WARN", "WF", _wfPending.Command, _lang.T("đang chạy", "running")));
|
||||
}
|
||||
else if (_prevWfRunning && !wf.IsRunning)
|
||||
{
|
||||
var newErr = wf.LastError != null && wf.LastError != _prevWfErr ? wf.LastError : null;
|
||||
if (newErr != null)
|
||||
Push(Line(CError, "ERR", "WF", _wfPending.Command, newErr));
|
||||
else
|
||||
{
|
||||
var elapsed = $"{(DateTime.Now - _wfPending.SentAt).TotalSeconds:F1}s";
|
||||
Push(Line(CSuccess, "DONE", "WF", _wfPending.Command, _lang.T("hoàn thành", "done"), $"{elapsed} │ cycles={wf.CompletedCycles}"));
|
||||
}
|
||||
_wfPending = null;
|
||||
}
|
||||
}
|
||||
|
||||
_prevImrBusy = wf.ImrBusy;
|
||||
_prevAmrBusy = wf.AmrBusy;
|
||||
_prevDobotBusy = wf.DobotBusy;
|
||||
_prevWfRunning = wf.IsRunning;
|
||||
_prevImrErr = wf.ImrExecError;
|
||||
_prevAmrErr = wf.AmrExecError;
|
||||
_prevDobotErr = wf.DobotExecError;
|
||||
_prevWfErr = wf.LastError;
|
||||
|
||||
if (IsDevMode)
|
||||
{
|
||||
if (wf.IsRunning != _devWfRunning)
|
||||
{
|
||||
DevPush("WF", wf.IsRunning ? "started" : "stopped");
|
||||
LogSystemSnapshot(wf.IsRunning ? "wf-start" : "wf-stop");
|
||||
_devWfRunning = wf.IsRunning;
|
||||
}
|
||||
if (wf.ImrBusy != _devImrBusy)
|
||||
{ if (_imrPending == null) DevPush("IMR", $"busy={wf.ImrBusy}" + (wf.ImrBusyLabel != null ? $" [{wf.ImrBusyLabel}]" : "")); _devImrBusy = wf.ImrBusy; }
|
||||
if (wf.AmrBusy != _devAmrBusy)
|
||||
{ if (_amrPending == null) DevPush("AMR", $"busy={wf.AmrBusy}" + (wf.AmrBusyLabel != null ? $" [{wf.AmrBusyLabel}]" : "")); _devAmrBusy = wf.AmrBusy; }
|
||||
if (wf.DobotBusy != _devDobotBusy)
|
||||
{ if (_dobotPending == null) DevPush("Dobot", $"busy={wf.DobotBusy}" + (wf.DobotBusyLabel != null ? $" [{wf.DobotBusyLabel}]" : "")); _devDobotBusy = wf.DobotBusy; }
|
||||
}
|
||||
}
|
||||
|
||||
private void OnAsrsChanged()
|
||||
{
|
||||
var asrs = _state.Asrs;
|
||||
|
||||
if (_asrsPending != null)
|
||||
{
|
||||
if (!_prevAsrsBusy && asrs.IsBusy)
|
||||
{
|
||||
Push(Line(CWarn, "WARN", "ASRS", _asrsPending.Command, _lang.T("đang thực hiện", "executing")));
|
||||
}
|
||||
else if (_prevAsrsBusy && !asrs.IsBusy)
|
||||
{
|
||||
var newErr = asrs.LastError != null && asrs.LastError != _prevAsrsErr ? asrs.LastError : null;
|
||||
if (newErr != null)
|
||||
Push(Line(CError, "ERR", "ASRS", _asrsPending.Command, newErr));
|
||||
else
|
||||
{
|
||||
var elapsed = $"{(DateTime.Now - _asrsPending.SentAt).TotalSeconds:F1}s";
|
||||
Push(Line(CSuccess, "DONE", "ASRS", _asrsPending.Command, _lang.T("hoàn thành", "done"), elapsed));
|
||||
}
|
||||
_asrsPending = null;
|
||||
}
|
||||
}
|
||||
|
||||
_prevAsrsBusy = asrs.IsBusy;
|
||||
_prevAsrsErr = asrs.LastError;
|
||||
|
||||
if (IsDevMode)
|
||||
{
|
||||
if (asrs.IsBusy != _devAsrsBusy)
|
||||
{ DevPush("ASRS", $"busy={asrs.IsBusy}"); _devAsrsBusy = asrs.IsBusy; }
|
||||
if (asrs.SAFETY_MODE != _devAsrsSafety)
|
||||
{
|
||||
DevPush("ASRS", $"safety={asrs.SAFETY_MODE}");
|
||||
LogSystemSnapshot($"asrs-safety={FormatBool(asrs.SAFETY_MODE)}");
|
||||
_devAsrsSafety = asrs.SAFETY_MODE;
|
||||
}
|
||||
DevSlot("X11", asrs.X11, ref _devX11); DevSlot("X12", asrs.X12, ref _devX12); DevSlot("X13", asrs.X13, ref _devX13);
|
||||
DevSlot("X21", asrs.X21, ref _devX21); DevSlot("X22", asrs.X22, ref _devX22); DevSlot("X23", asrs.X23, ref _devX23);
|
||||
DevSlot("X31", asrs.X31, ref _devX31); DevSlot("X32", asrs.X32, ref _devX32); DevSlot("X33", asrs.X33, ref _devX33);
|
||||
DevSlot("X41", asrs.X41, ref _devX41); DevSlot("X42", asrs.X42, ref _devX42); DevSlot("X43", asrs.X43, ref _devX43);
|
||||
}
|
||||
}
|
||||
|
||||
private void OnConveyorChanged()
|
||||
{
|
||||
var conv = _state.Conveyor;
|
||||
|
||||
if (IsDevMode)
|
||||
{
|
||||
var pendingKey = _conveyorPending?.CoilKey; // skip coil already tracked by pending section
|
||||
DevCoil("C1.In", conv.C1In, ref _devC1In, pendingKey);
|
||||
DevCoil("C1.Out", conv.C1Out, ref _devC1Out, pendingKey);
|
||||
DevCoil("C1.IMRin", conv.C1IMRin, ref _devC1IMRin, pendingKey);
|
||||
DevCoil("C1.IMRout", conv.C1IMRout, ref _devC1IMRout, pendingKey);
|
||||
DevCoil("C1.Goods", conv.C1HasGoods, ref _devC1HasGoods, pendingKey);
|
||||
DevCoil("C1.Empty", conv.C1NotGoods, ref _devC1NotGoods, pendingKey);
|
||||
DevCoil("C1.Ready", conv.C1Ready, ref _devC1Ready, pendingKey);
|
||||
DevCoil("C2.In", conv.C2In, ref _devC2In, pendingKey);
|
||||
DevCoil("C2.Out", conv.C2Out, ref _devC2Out, pendingKey);
|
||||
DevCoil("C2.Goods", conv.C2HasGoods, ref _devC2HasGoods, pendingKey);
|
||||
DevCoil("C2.Empty", conv.C2NotGoods, ref _devC2NotGoods, pendingKey);
|
||||
DevCoil("C2.Ready", conv.C2Ready, ref _devC2Ready, pendingKey);
|
||||
}
|
||||
|
||||
if (_conveyorPending == null) return;
|
||||
|
||||
var key = _conveyorPending.CoilKey;
|
||||
var current = GetCoil(conv, key);
|
||||
var prev = _conveyorTargetPrev;
|
||||
|
||||
if (current.HasValue)
|
||||
{
|
||||
if (_conveyorPending.ExpectedValue)
|
||||
{
|
||||
if (!_conveyorPending.CoilReached && current.Value)
|
||||
{
|
||||
Push(Line(CWarn, "WARN", "CV", "SetCoil", $"{key}=true"));
|
||||
_conveyorPending = _conveyorPending with { CoilReached = true };
|
||||
}
|
||||
else if (_conveyorPending.CoilReached && !current.Value)
|
||||
{
|
||||
Push(Line(CSuccess, "DONE", "CV", "SetCoil", $"{key} reset"));
|
||||
_conveyorPending = null;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
if (prev != false && !current.Value)
|
||||
{
|
||||
Push(Line(CSuccess, "DONE", "CV", "SetCoil", $"{key}=false"));
|
||||
_conveyorPending = null;
|
||||
}
|
||||
}
|
||||
|
||||
_conveyorTargetPrev = current;
|
||||
}
|
||||
}
|
||||
|
||||
private static bool? GetCoil(ConveyorPushDto conv, string key) =>
|
||||
key.ToLowerInvariant().Replace("-", "") switch
|
||||
{
|
||||
"c1in" => conv.C1In,
|
||||
"c1out" => conv.C1Out,
|
||||
"c1imrin" => conv.C1IMRin,
|
||||
"c1imrout" => conv.C1IMRout,
|
||||
"c1hasgoods" => conv.C1HasGoods,
|
||||
"c1notgoods" => conv.C1NotGoods,
|
||||
"c1ready" => conv.C1Ready,
|
||||
"c2in" => conv.C2In,
|
||||
"c2out" => conv.C2Out,
|
||||
"c2hasgoods" => conv.C2HasGoods,
|
||||
"c2notgoods" => conv.C2NotGoods,
|
||||
"c2ready" => conv.C2Ready,
|
||||
_ => null
|
||||
};
|
||||
|
||||
// ── Dev helpers ───────────────────────────────────────────────────────
|
||||
|
||||
/// <summary>DEV line without a specific command (state change, online, busy…).</summary>
|
||||
private void DevPush(string device, string msg) =>
|
||||
Push(LineRaw(CDev, "DEV", device, msg));
|
||||
|
||||
/// <summary>DEV line with command context (NBR, action status…).</summary>
|
||||
private void DevPush(string device, string command, string status) =>
|
||||
Push(Line(CDev, "DEV", device, command, status));
|
||||
|
||||
private void DevCoil(string name, bool? current, ref bool? prev, string? pendingKey = null)
|
||||
{
|
||||
if (current == prev) return;
|
||||
var key = name.Replace(".", "").Replace("IMR", "imr").ToLowerInvariant();
|
||||
if (pendingKey == null || !pendingKey.Equals(key, StringComparison.OrdinalIgnoreCase))
|
||||
Push(LineRaw(CDev, "DEV", "CV", $"{name}={current}"));
|
||||
prev = current;
|
||||
}
|
||||
|
||||
private void DevSlot(string name, bool? current, ref bool? prev)
|
||||
{
|
||||
if (current == prev) return;
|
||||
Push(LineRaw(CDev, "DEV", "ASRS", $"{name}={current}"));
|
||||
prev = current;
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────────────
|
||||
|
||||
private void LogSystemSnapshot(string trigger)
|
||||
{
|
||||
var mode = _state.System.IsSimulation ? "SIM" : "REAL";
|
||||
var wf = _state.Workflow;
|
||||
var imr = _state.Imr;
|
||||
var amr = _state.Amr;
|
||||
var conv = _state.Conveyor;
|
||||
var asrs = _state.Asrs;
|
||||
|
||||
DevPush("SYS",
|
||||
$"snapshot={trigger} | mode={mode} | wf={DescribeWorkflow(wf)}");
|
||||
DevPush("SYS",
|
||||
$"IMR[{DescribeRobot(imr)}] | AMR[{DescribeRobot(amr)}] | CV[{DescribeConveyor(conv)}] | ASRS[{DescribeAsrs(asrs)}]");
|
||||
}
|
||||
|
||||
private static bool ShouldCaptureSystemSnapshot(NotificationDto notification, string? source)
|
||||
{
|
||||
if (notification.Level is "warning" or "error")
|
||||
return true;
|
||||
|
||||
var normalized = (source ?? notification.Source ?? string.Empty).ToUpperInvariant();
|
||||
if (normalized.Contains("FLOW") || normalized == "WF")
|
||||
{
|
||||
var command = notification.Command ?? notification.Message;
|
||||
return command.Contains("Start", StringComparison.OrdinalIgnoreCase)
|
||||
|| command.Contains("Done", StringComparison.OrdinalIgnoreCase)
|
||||
|| command.Contains("Hủy", StringComparison.OrdinalIgnoreCase)
|
||||
|| command.Contains("Cancel", StringComparison.OrdinalIgnoreCase);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private static string? TryExtractSource(string message)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(message))
|
||||
return null;
|
||||
|
||||
var text = message.Trim();
|
||||
if (text.StartsWith('['))
|
||||
{
|
||||
var end = text.IndexOf(']');
|
||||
if (end > 1)
|
||||
return text[1..end].Trim();
|
||||
}
|
||||
|
||||
var colon = text.IndexOf(": ", StringComparison.Ordinal);
|
||||
if (colon > 0)
|
||||
{
|
||||
var head = text[..colon].Trim();
|
||||
if (head.Length <= 24)
|
||||
return head;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private static string MapNotificationDevice(string? source)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(source))
|
||||
return "Sys";
|
||||
|
||||
var prefix = source.Trim().ToUpperInvariant();
|
||||
return prefix switch
|
||||
{
|
||||
"IMR" => "IMR",
|
||||
"AMR" => "AMR",
|
||||
"DOBOT" => "Dobot",
|
||||
"ASRS" => "ASRS",
|
||||
"WF" or "FLOW" => "WF",
|
||||
"OPC" => "OPC",
|
||||
"VDA" => "VDA",
|
||||
"SIM" => "Sim",
|
||||
"T3" => "T3",
|
||||
"WAIT" => "Wait",
|
||||
"INIT" => "Init",
|
||||
var p when p.StartsWith("FLOW+ASRS") => "WF+AS",
|
||||
var p when p.StartsWith("CONV") => "Conv",
|
||||
var p when p.StartsWith("CONVEYOR") => "Conv",
|
||||
var p when p.StartsWith("STEP") => "WF",
|
||||
var p => p.Length > 6 ? p[..6] : p,
|
||||
};
|
||||
}
|
||||
|
||||
private static string DescribeWorkflow(WorkflowStateDto workflow)
|
||||
{
|
||||
var state = workflow.IsRunning ? "running" : "idle";
|
||||
var last = string.IsNullOrWhiteSpace(workflow.LastError) ? "ok" : $"err={workflow.LastError}";
|
||||
return $"{state} cycles={workflow.CompletedCycles} imrBusy={workflow.ImrBusy} amrBusy={workflow.AmrBusy} dobotBusy={workflow.DobotBusy} {last}";
|
||||
}
|
||||
|
||||
private static string DescribeRobot(RobotStateDto robot)
|
||||
{
|
||||
var action = robot.Actions.Length > 0
|
||||
? $"{robot.Actions[0].ActionID}/{robot.Actions[0].ActionStatus ?? "?"}"
|
||||
: "-";
|
||||
var errors = robot.Errors.Count > 0 ? robot.Errors.Count.ToString() : "0";
|
||||
return $"on={robot.IsOnline} nbr={FormatBool(robot.NewBaseRequest)} pos=({robot.X:F2},{robot.Y:F2}) act={action} err={errors}";
|
||||
}
|
||||
|
||||
private static string DescribeConveyor(ConveyorPushDto conveyor)
|
||||
=> $"C1[in={FormatBool(conveyor.C1In)},out={FormatBool(conveyor.C1Out)},goods={FormatBool(conveyor.C1HasGoods)},empty={FormatBool(conveyor.C1NotGoods)},ready={FormatBool(conveyor.C1Ready)}] " +
|
||||
$"C2[in={FormatBool(conveyor.C2In)},out={FormatBool(conveyor.C2Out)},goods={FormatBool(conveyor.C2HasGoods)},empty={FormatBool(conveyor.C2NotGoods)},ready={FormatBool(conveyor.C2Ready)}]" +
|
||||
$"{(string.IsNullOrWhiteSpace(conveyor.WriteError) ? string.Empty : $" writeErr={conveyor.WriteError}")}";
|
||||
|
||||
private static string DescribeAsrs(AsrsPushDto asrs)
|
||||
{
|
||||
var locks = asrs.LockedOps.Length > 0 ? string.Join(",", asrs.LockedOps) : "-";
|
||||
var error = string.IsNullOrWhiteSpace(asrs.LastError) ? "ok" : asrs.LastError;
|
||||
return $"busy={asrs.IsBusy} offline={asrs.IsOffline} safety={FormatBool(asrs.SAFETY_MODE)} locks={locks} err={error}";
|
||||
}
|
||||
|
||||
private static string FormatBool(bool? value) => value switch
|
||||
{
|
||||
true => "T",
|
||||
false => "F",
|
||||
null => "?"
|
||||
};
|
||||
|
||||
private void Push(string html)
|
||||
{
|
||||
_lines.Insert(0, html);
|
||||
Trim();
|
||||
LogChanged?.Invoke();
|
||||
}
|
||||
|
||||
private void Trim() { while (_lines.Count > 1000) _lines.RemoveAt(_lines.Count - 1); }
|
||||
|
||||
// Delegates → LogFormat (single source of truth)
|
||||
private static string Line(string color, string badge, string device, string command, string status, string? detail = null)
|
||||
=> LogFormat.Line(color, badge, device, command, status, detail);
|
||||
|
||||
private static string LineRaw(string color, string badge, string device, string msg)
|
||||
=> LogFormat.LineRaw(color, badge, device, msg);
|
||||
|
||||
/// X1A / X2A / X3A / X1B / X2B / X3B — fire-and-forget, không cần track pending
|
||||
private static bool IsXCycleCommand(string cmd) =>
|
||||
cmd.Length == 3 && cmd[0] == 'X' && cmd[1] is '1' or '2' or '3' && cmd[2] is 'A' or 'B';
|
||||
|
||||
private record PendingCmd(string Command, string? Params, bool IsMove, DateTime SentAt);
|
||||
private record PendingConveyorCmd(string CoilKey, bool ExpectedValue, bool CoilReached = false);
|
||||
}
|
||||
147
Lab505.Client/Services/StateService.cs
Normal file
147
Lab505.Client/Services/StateService.cs
Normal file
@@ -0,0 +1,147 @@
|
||||
using Lab505.Shared;
|
||||
using Microsoft.AspNetCore.SignalR.Client;
|
||||
|
||||
namespace Lab505.Client.Services;
|
||||
|
||||
public class StateService : IAsyncDisposable
|
||||
{
|
||||
private HubConnection? _hub;
|
||||
private readonly HttpClient _http;
|
||||
|
||||
public RobotStateDto Imr { get; private set; } = EmptyRobot;
|
||||
public RobotStateDto Amr { get; private set; } = EmptyRobot;
|
||||
public ConveyorPushDto Conveyor { get; private set; } = EmptyConveyor;
|
||||
public AsrsPushDto Asrs { get; private set; } = EmptyAsrs;
|
||||
public WorkflowStateDto Workflow { get; private set; } = EmptyWorkflow;
|
||||
public SystemStateDto System { get; private set; } = new(false, false);
|
||||
|
||||
public LockStateDto? LockState { get; private set; }
|
||||
|
||||
public bool CanControl => true;
|
||||
public bool IsConnected => _hub?.State == HubConnectionState.Connected;
|
||||
|
||||
public event Action? ImrChanged;
|
||||
public event Action? AmrChanged;
|
||||
public event Action? ConveyorChanged;
|
||||
public event Action? AsrsChanged;
|
||||
public event Action? WorkflowChanged;
|
||||
public event Action? SystemChanged;
|
||||
public event Action? LockStateChanged;
|
||||
public event Action<NotificationDto>? NotificationReceived;
|
||||
|
||||
/// <summary>Fires khi stack thay đổi do T3 push ModeChangedEvent — UI dùng để update nút SIM/REAL.</summary>
|
||||
public event Action<bool>? StackChanged;
|
||||
|
||||
public StateService(HttpClient http) => _http = http;
|
||||
|
||||
/// <summary>
|
||||
/// Chuyển client sang đúng SignalR group sau khi user thay đổi stack (real ↔ sim).
|
||||
/// Gọi sau khi POST /api/mode/real hoặc /api/mode/simulation thành công.
|
||||
/// </summary>
|
||||
public async Task SwitchStackAsync(bool useReal)
|
||||
{
|
||||
if (_hub?.State == HubConnectionState.Connected)
|
||||
await _hub.InvokeAsync("JoinStack", useReal);
|
||||
}
|
||||
|
||||
public async Task StartAsync()
|
||||
{
|
||||
if (_hub != null) return;
|
||||
if (!OperatingSystem.IsBrowser()) return;
|
||||
|
||||
_hub = new HubConnectionBuilder()
|
||||
.WithUrl(new Uri(_http.BaseAddress!, HubContracts.StateHubRoute))
|
||||
.WithAutomaticReconnect()
|
||||
.Build();
|
||||
|
||||
RegisterHubHandlers();
|
||||
await _hub.StartAsync();
|
||||
}
|
||||
|
||||
private void RegisterHubHandlers()
|
||||
{
|
||||
if (_hub is null)
|
||||
return;
|
||||
|
||||
_hub.On<RobotStateDto>(HubContracts.ImrStateEvent, dto =>
|
||||
{
|
||||
Imr = dto;
|
||||
ImrChanged?.Invoke();
|
||||
});
|
||||
|
||||
_hub.On<RobotStateDto>(HubContracts.AmrStateEvent, dto =>
|
||||
{
|
||||
Amr = dto;
|
||||
AmrChanged?.Invoke();
|
||||
});
|
||||
|
||||
_hub.On<ConveyorPushDto>(HubContracts.ConveyorStateEvent, dto =>
|
||||
{
|
||||
Conveyor = dto;
|
||||
ConveyorChanged?.Invoke();
|
||||
});
|
||||
|
||||
_hub.On<AsrsPushDto>(HubContracts.AsrsStateEvent, dto =>
|
||||
{
|
||||
Asrs = dto;
|
||||
AsrsChanged?.Invoke();
|
||||
});
|
||||
|
||||
_hub.On<WorkflowStateDto>(HubContracts.WorkflowStateEvent, dto =>
|
||||
{
|
||||
Workflow = dto;
|
||||
WorkflowChanged?.Invoke();
|
||||
});
|
||||
|
||||
_hub.On<SystemStateDto>(HubContracts.SystemStateEvent, dto =>
|
||||
{
|
||||
System = dto;
|
||||
SystemChanged?.Invoke();
|
||||
});
|
||||
|
||||
_hub.On<NotificationDto>(HubContracts.NotificationEvent, dto =>
|
||||
{
|
||||
NotificationReceived?.Invoke(dto);
|
||||
});
|
||||
|
||||
_hub.On<LockStateDto>(HubContracts.LockStateEvent, dto =>
|
||||
{
|
||||
LockState = dto;
|
||||
LockStateChanged?.Invoke();
|
||||
});
|
||||
|
||||
// T3 đổi mode server-side → server push event → client tự JoinStack đúng group + notify UI
|
||||
_hub.On<bool>(HubContracts.ModeChangedEvent, async useReal =>
|
||||
{
|
||||
await SwitchStackAsync(useReal);
|
||||
StackChanged?.Invoke(useReal);
|
||||
});
|
||||
}
|
||||
|
||||
public async ValueTask DisposeAsync()
|
||||
{
|
||||
if (_hub != null)
|
||||
{
|
||||
await _hub.DisposeAsync();
|
||||
_hub = null;
|
||||
}
|
||||
}
|
||||
|
||||
// ── Helpers ───────────────────────────────────────────────────
|
||||
|
||||
public bool AsrsIsLocked(string key) => Asrs.LockedOps.Contains(key);
|
||||
|
||||
// ── Defaults ─────────────────────────────────────────────────
|
||||
|
||||
private static readonly RobotStateDto EmptyRobot =
|
||||
new(0, 0, false, null, new(), Array.Empty<ActionStateDto>(), "", 9999, Array.Empty<RobotErrorDto>());
|
||||
|
||||
private static readonly ConveyorPushDto EmptyConveyor =
|
||||
new(null, null, null, null, null, null, null, null, null, null, null, null, null);
|
||||
|
||||
private static readonly AsrsPushDto EmptyAsrs =
|
||||
new(null, null, null, null, null, null, null, null, null, null, null, null, null, true, false, Array.Empty<string>(), null);
|
||||
|
||||
private static readonly WorkflowStateDto EmptyWorkflow =
|
||||
new(false, null, 0, "", "", false, null, null, false, null, null, null, null, false, null, null, null);
|
||||
}
|
||||
Reference in New Issue
Block a user