Files
Lab505/Lab505.Client/Services/ScriptLogService.cs
2026-10-22 14:31:58 +07:00

805 lines
36 KiB
C#

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;
}
/// <summary>
/// ASRS qua OPC UA: chỉ log lệnh gửi và lỗi bị từ chối ngay (HTTP).
/// Kết quả thực thi (hoàn thành / lỗi / timeout) đến qua notification "ASRS" từ server.
/// </summary>
public void LogAsrsOpcCommand(string command, string? @params = null)
=> Push(Line(CInfo, "INFO", "ASRS", command, _lang.T("→ gửi", "→ sent"), @params));
public void LogAsrsOpcRejected(string command, string? error)
=> Push(Line(CError, "ERR", "ASRS", command, _lang.T("✗ từ chối", "✗ rejected"), error));
// ── 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);
}