diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..547a964
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,4 @@
+bin/
+obj/
+.vs/
+*.user
diff --git a/Lab505.Client/Pages/AsrsOpcPanel.razor b/Lab505.Client/Pages/AsrsOpcPanel.razor
new file mode 100644
index 0000000..7434bb5
--- /dev/null
+++ b/Lab505.Client/Pages/AsrsOpcPanel.razor
@@ -0,0 +1,184 @@
+@implements IAsyncDisposable
+
+
+
+
+ ASRS · OPC UA
+
+
+
+
+
+
+ @StatusText
+ @if (S.Available && S.Online)
+ {
+
+ Homed: @Fmt(S.Homed) | Busy: @Fmt(S.Busy) | Fault: @Fmt(S.Fault)
+
+ }
+
+
+
+ @if (!string.IsNullOrEmpty(S.LastError))
+ {
+ @S.LastError
+ }
+
+ @if (_expanded && S.Available)
+ {
+
+ Kho (cột × tầng) — chọn ô@(_from is null ? "" : $": {Name(_from.Value)}")@(_to is null ? "" : $" → {Name(_to.Value)}")
+
+
+ @for (int shelf = AsrsOpcLayout.Shelves; shelf >= 1; shelf--)
+ {
+ T@(shelf)
+ @for (int col = 1; col <= AsrsOpcLayout.Columns; col++)
+ {
+ var cell = (col, shelf);
+
+ }
+ }
+
+
+ Băng tải
+
+ BT1 · Trái
+ BT2 · Phải
+
+
+ Lệnh
+
+ Retrieve
+ Store
+ Move
+ StoreAny
+ Home
+
+ }
+
+
+
+@code {
+ [Inject] StateService State { get; set; } = default!;
+ [Inject] CommandService Cmd { get; set; } = default!;
+
+ private bool _expanded = true;
+ private void Toggle() => _expanded = !_expanded;
+
+ private int _conveyor = 1;
+ private (int Col, int Shelf)? _from;
+ private (int Col, int Shelf)? _to;
+
+ private AsrsOpcPushDto S => State.AsrsOpc;
+
+ protected override async Task OnInitializedAsync()
+ {
+ await State.StartAsync();
+ State.AsrsOpcChanged += Refresh;
+ }
+
+ public ValueTask DisposeAsync()
+ {
+ State.AsrsOpcChanged -= Refresh;
+ return ValueTask.CompletedTask;
+ }
+
+ private void Refresh() => InvokeAsync(StateHasChanged);
+
+ // ── Status ──────────────────────────────────────────────────────────
+ // PLC giữ Busy=1 thêm ~3s sau mỗi lệnh để chờ lệnh kế tiếp chạy nối luôn → vẫn cho gửi lệnh.
+ private string StatusText =>
+ !S.Available ? "CHỈ CÓ TRÊN REAL STACK" :
+ !S.Online ? "OFFLINE" :
+ S.Fault == true ? "FAULT (E-STOP / SAFETY)" :
+ S.DriverBusy ? $"ĐANG CHẠY: {S.CurrentOp}" :
+ S.Busy == true ? "SẴN SÀNG · PLC CHỜ LỆNH KẾ TIẾP" :
+ "SẴN SÀNG";
+
+ private Color StatusColor =>
+ !S.Available || !S.Online ? Color.Default :
+ S.Fault == true ? Color.Error :
+ S.DriverBusy ? Color.Info :
+ Color.Success;
+
+ private static string Fmt(bool? v) => v switch { true => "1", false => "0", _ => "-" };
+
+ // ── Slots ───────────────────────────────────────────────────────────
+ private bool? Occ((int Col, int Shelf) c) => S.Occupied.ElementAtOrDefault(AsrsOpcLayout.SlotIndex(c.Col, c.Shelf));
+
+ private static string Name((int Col, int Shelf) c) => $"{c.Col}.{c.Shelf}";
+
+ private string CellClass((int Col, int Shelf) c)
+ {
+ var cls = Occ(c) switch { true => "slot full", false => "slot", _ => "slot unknown" };
+ if (_from == c) cls += " sel-from";
+ if (_to == c) cls += " sel-to";
+ return cls;
+ }
+
+ /// Click 1 = ô chính (Retrieve/Store/nguồn Move). Click 2 ô khác = ô đích Move. Click lại = bỏ chọn.
+ private void Pick((int Col, int Shelf) c)
+ {
+ if (_from == c) { _from = _to; _to = null; }
+ else if (_to == c) { _to = null; }
+ else if (_from is null) _from = c;
+ else _to = c;
+ }
+
+ // ── Enable rules (server vẫn kiểm tra lại) ─────────────────────────
+ private bool CanCommand => State.CanControl && S.Available && S.Online
+ && S.Fault != true && !S.DriverBusy;
+
+ private bool CanRetrieve => CanCommand && _from is { } f && _to is null && Occ(f) == true;
+ private bool CanStore => CanCommand && _from is { } f && _to is null && Occ(f) == false;
+ private bool CanMove => CanCommand && _from is { } f && _to is { } t && Occ(f) == true && Occ(t) == false;
+ private bool CanStoreAny => CanCommand && S.Occupied.Any(o => o == false);
+
+ // ── Commands ───────────────────────────────────────────────────────
+ private async Task Retrieve()
+ {
+ var f = _from!.Value; ClearSel();
+ await Cmd.AsrsOpcRetrieveAsync(f.Col, f.Shelf, _conveyor);
+ }
+
+ private async Task Store()
+ {
+ var f = _from!.Value; ClearSel();
+ await Cmd.AsrsOpcStoreAsync(f.Col, f.Shelf, _conveyor);
+ }
+
+ private async Task Move()
+ {
+ var f = _from!.Value; var t = _to!.Value; ClearSel();
+ await Cmd.AsrsOpcMoveAsync(f.Col, f.Shelf, t.Col, t.Shelf);
+ }
+
+ private Task StoreAny() => Cmd.AsrsOpcStoreAnyAsync(_conveyor);
+ private Task Home() => Cmd.AsrsOpcHomeAsync();
+
+ private void ClearSel() { _from = null; _to = null; }
+}
+
+
diff --git a/Lab505.Client/Pages/Home.razor b/Lab505.Client/Pages/Home.razor
index 88348a5..b0ca2c9 100644
--- a/Lab505.Client/Pages/Home.razor
+++ b/Lab505.Client/Pages/Home.razor
@@ -92,7 +92,7 @@
-
+
@code {
diff --git a/Lab505.Client/Pages/ImrAmrStatusPanel.razor b/Lab505.Client/Pages/ImrAmrStatusPanel.razor
index 790a20d..020a789 100644
--- a/Lab505.Client/Pages/ImrAmrStatusPanel.razor
+++ b/Lab505.Client/Pages/ImrAmrStatusPanel.razor
@@ -4,12 +4,12 @@
@RobotRow("IMR", State.Imr)
@RobotRow("AMR", State.Amr)
- ASRS
Safety
+ Color="@(State.AsrsOpc.Fault == true ? Color.Error : State.AsrsOpc.Fault == false ? Color.Success : Color.Default)"
+ Variant="@(State.AsrsOpc.Fault is null ? Variant.Outlined : Variant.Filled)"
+ Style="height:22px;font-size:11px;margin:0;flex-shrink:0;">@(State.AsrsOpc.Fault == true ? "Fault" : "Safety")
@@ -21,7 +21,7 @@
await State.StartAsync();
State.ImrChanged += Refresh;
State.AmrChanged += Refresh;
- State.AsrsChanged += Refresh;
+ State.AsrsOpcChanged += Refresh;
State.WorkflowChanged += Refresh;
}
@@ -29,7 +29,7 @@
{
State.ImrChanged -= Refresh;
State.AmrChanged -= Refresh;
- State.AsrsChanged -= Refresh;
+ State.AsrsOpcChanged -= Refresh;
State.WorkflowChanged -= Refresh;
return ValueTask.CompletedTask;
}
diff --git a/Lab505.Client/Pages/StatusPanel.razor b/Lab505.Client/Pages/StatusPanel.razor
index 6a58290..ff9e2b1 100644
--- a/Lab505.Client/Pages/StatusPanel.razor
+++ b/Lab505.Client/Pages/StatusPanel.razor
@@ -26,13 +26,13 @@
- @* ── ASRS grid ── *@
+ @* ── ASRS grid — Slot.{cột}.{tầng}.Occupied từ gateway OPC UA, tầng cao nhất ở trên ── *@
@foreach (var row in AsrsRows)
{
@foreach (var cell in row.Cells)
{
- bool on = cell.Val == true && !State.Asrs.IsOffline;
+ bool on = cell.Val == true && State.AsrsOpc.Online;
new[]
- {
- ("L4", new (string, bool?)[] { ("41", State.Asrs.X41), ("42", State.Asrs.X42), ("43", State.Asrs.X43) }),
- ("L3", new (string, bool?)[] { ("31", State.Asrs.X31), ("32", State.Asrs.X32), ("33", State.Asrs.X33) }),
- ("L2", new (string, bool?)[] { ("21", State.Asrs.X21), ("22", State.Asrs.X22), ("23", State.Asrs.X23) }),
- ("L1", new (string, bool?)[] { ("11", State.Asrs.X11), ("12", State.Asrs.X12), ("13", State.Asrs.X13) }),
- };
+ private (string RowLabel, (string Label, bool? Val)[] Cells)[] AsrsRows =>
+ Enumerable.Range(1, AsrsOpcLayout.Shelves).Reverse()
+ .Select(shelf => ($"T{shelf}",
+ Enumerable.Range(1, AsrsOpcLayout.Columns)
+ .Select(col => ($"{col}.{shelf}",
+ State.AsrsOpc.Occupied.ElementAtOrDefault(AsrsOpcLayout.SlotIndex(col, shelf))))
+ .ToArray()))
+ .ToArray();
}
diff --git a/Lab505.Client/Services/CommandService.cs b/Lab505.Client/Services/CommandService.cs
index a802798..cf53161 100644
--- a/Lab505.Client/Services/CommandService.cs
+++ b/Lab505.Client/Services/CommandService.cs
@@ -169,6 +169,48 @@ public class CommandService
return PostAsync($"/api/asrs/workflow/{op}", null, ct, "ASRS");
}
+ // ── ASRS qua OPC UA (gateway) ─────────────────────────────────────────
+ public Task AsrsOpcHomeAsync(CancellationToken ct = default)
+ => PostAsrsOpcAsync("Home", null, "/api/asrs/opc/home", null, ct);
+
+ public Task AsrsOpcRetrieveAsync(int column, int shelf, int conveyor, CancellationToken ct = default)
+ => PostAsrsOpcAsync("Retrieve", $"{column}.{shelf} → BT{conveyor}", "/api/asrs/opc/retrieve",
+ new { Column = column, Shelf = shelf, Conveyor = conveyor }, ct);
+
+ public Task AsrsOpcStoreAsync(int column, int shelf, int conveyor, CancellationToken ct = default)
+ => PostAsrsOpcAsync("Store", $"BT{conveyor} → {column}.{shelf}", "/api/asrs/opc/store",
+ new { Column = column, Shelf = shelf, Conveyor = conveyor }, ct);
+
+ public Task AsrsOpcStoreAnyAsync(int conveyor, CancellationToken ct = default)
+ => PostAsrsOpcAsync("StoreAny", $"BT{conveyor}", "/api/asrs/opc/store-any",
+ new { Conveyor = conveyor }, ct);
+
+ public Task AsrsOpcMoveAsync(int fromColumn, int fromShelf, int toColumn, int toShelf, CancellationToken ct = default)
+ => PostAsrsOpcAsync("Move", $"{fromColumn}.{fromShelf} → {toColumn}.{toShelf}", "/api/asrs/opc/move",
+ new { FromColumn = fromColumn, FromShelf = fromShelf, ToColumn = toColumn, ToShelf = toShelf }, ct);
+
+ private async Task PostAsrsOpcAsync(string command, string? @params, string url, object? body, CancellationToken ct)
+ {
+ _log.LogAsrsOpcCommand(command, @params);
+ 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) return;
+
+ string? error = null;
+ try { error = (await resp.Content.ReadFromJsonAsync(cancellationToken: ct))?.Error; }
+ catch { }
+ _log.LogAsrsOpcRejected(command, error ?? $"HTTP {(int)resp.StatusCode}");
+ }
+ catch (OperationCanceledException) { throw; }
+ catch (Exception ex) { _log.LogAsrsOpcRejected(command, ex.Message); }
+ }
+
+ private sealed record ApiErrorBody(string? Error);
+
// ── Workflow ──────────────────────────────────────────────────────────
public Task WorkflowX1AAsync(int times, int ng, CancellationToken ct = default)
{
diff --git a/Lab505.Client/Services/ScriptLogService.cs b/Lab505.Client/Services/ScriptLogService.cs
index 752e25f..75db88d 100644
--- a/Lab505.Client/Services/ScriptLogService.cs
+++ b/Lab505.Client/Services/ScriptLogService.cs
@@ -279,6 +279,16 @@ public class ScriptLogService : IDisposable
if (!ok) _conveyorPending = null;
}
+ ///
+ /// 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.
+ ///
+ 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()
diff --git a/Lab505.Client/Services/StateService.cs b/Lab505.Client/Services/StateService.cs
index 8816e18..6fff638 100644
--- a/Lab505.Client/Services/StateService.cs
+++ b/Lab505.Client/Services/StateService.cs
@@ -12,6 +12,7 @@ public class StateService : IAsyncDisposable
public RobotStateDto Amr { get; private set; } = EmptyRobot;
public ConveyorPushDto Conveyor { get; private set; } = EmptyConveyor;
public AsrsPushDto Asrs { get; private set; } = EmptyAsrs;
+ public AsrsOpcPushDto AsrsOpc { get; private set; } = EmptyAsrsOpc;
public WorkflowStateDto Workflow { get; private set; } = EmptyWorkflow;
public SystemStateDto System { get; private set; } = new(false, false);
@@ -24,6 +25,7 @@ public class StateService : IAsyncDisposable
public event Action? AmrChanged;
public event Action? ConveyorChanged;
public event Action? AsrsChanged;
+ public event Action? AsrsOpcChanged;
public event Action? WorkflowChanged;
public event Action? SystemChanged;
public event Action? LockStateChanged;
@@ -87,6 +89,12 @@ public class StateService : IAsyncDisposable
AsrsChanged?.Invoke();
});
+ _hub.On(HubContracts.AsrsOpcStateEvent, dto =>
+ {
+ AsrsOpc = dto;
+ AsrsOpcChanged?.Invoke();
+ });
+
_hub.On(HubContracts.WorkflowStateEvent, dto =>
{
Workflow = dto;
@@ -142,6 +150,9 @@ public class StateService : IAsyncDisposable
private static readonly AsrsPushDto EmptyAsrs =
new(null, null, null, null, null, null, null, null, null, null, null, null, null, true, false, Array.Empty(), null);
+ private static readonly AsrsOpcPushDto EmptyAsrsOpc =
+ new(false, false, null, null, null, null, new bool?[AsrsOpcLayout.SlotCount], false, null, null);
+
private static readonly WorkflowStateDto EmptyWorkflow =
new(false, null, 0, "", "", false, null, null, false, null, null, null, null, false, null, null, null);
}
diff --git a/Lab505.Shared/AsrsOpcPushDto.cs b/Lab505.Shared/AsrsOpcPushDto.cs
new file mode 100644
index 0000000..39125ef
--- /dev/null
+++ b/Lab505.Shared/AsrsOpcPushDto.cs
@@ -0,0 +1,31 @@
+namespace Lab505.Shared;
+
+///
+/// Bố cục kho ASRS theo gateway AsrsOpcUaServer: 3 cột × 4 tầng.
+/// Slot index giống PLC (PlcAddressMap.ToSlotIndex): (shelf-1)*3 + (col-1).
+///
+public static class AsrsOpcLayout
+{
+ public const int Columns = 3;
+ public const int Shelves = 4;
+ public const int SlotCount = Columns * Shelves;
+
+ public static int SlotIndex(int column, int shelf) => (shelf - 1) * Columns + (column - 1);
+}
+
+///
+/// State ASRS đọc qua OPC UA (gateway AsrsOpcUaServer), push qua SignalR.
+/// Available=false trên sim stack (ASRS OPC UA chỉ có trên real stack).
+///
+public record AsrsOpcPushDto(
+ bool Available,
+ bool Online,
+ bool? Homed,
+ bool? Ready,
+ bool? Busy,
+ bool? Fault,
+ bool?[] Occupied, // AsrsOpcLayout.SlotCount phần tử, index = AsrsOpcLayout.SlotIndex(col, shelf)
+ bool DriverBusy, // Lab505 đang thực thi 1 lệnh ASRS
+ string? CurrentOp,
+ string? LastError
+);
diff --git a/Lab505.Shared/HubContracts.cs b/Lab505.Shared/HubContracts.cs
index 5984bc5..9bc76c5 100644
--- a/Lab505.Shared/HubContracts.cs
+++ b/Lab505.Shared/HubContracts.cs
@@ -14,6 +14,7 @@ public static class HubContracts
public const string AmrStateEvent = "amr-state";
public const string ConveyorStateEvent = "conveyor-state";
public const string AsrsStateEvent = "asrs-state";
+ public const string AsrsOpcStateEvent = "asrs-opc-state";
public const string WorkflowStateEvent = "workflow-state";
public const string SystemStateEvent = "system-state";
diff --git a/Lab505/Application/Contexts/IDriverContext.cs b/Lab505/Application/Contexts/IDriverContext.cs
index ed201a9..c7c185b 100644
--- a/Lab505/Application/Contexts/IDriverContext.cs
+++ b/Lab505/Application/Contexts/IDriverContext.cs
@@ -32,6 +32,9 @@ public interface IDriverContext
/// null đối với sim stack (không có OPC UA riêng cho sim IMR).
ImrOpcUaDriver? ImrOpc { get; }
+ /// ASRS qua gateway OPC UA — null đối với sim stack.
+ AsrsOpcDriver? AsrsOpc { get; }
+
// ── State ─────────────────────────────────────────────────────────────
RobotState ImrState { get; }
RobotState AmrState { get; }
diff --git a/Lab505/Application/Contexts/RealDriverContext.cs b/Lab505/Application/Contexts/RealDriverContext.cs
index 8d0ef5e..3e572ce 100644
--- a/Lab505/Application/Contexts/RealDriverContext.cs
+++ b/Lab505/Application/Contexts/RealDriverContext.cs
@@ -28,6 +28,7 @@ public sealed class RealDriverContext : IDriverContext
public IAsrsDriver Asrs { get; }
public IDobotDriver Dobot { get; }
public ImrOpcUaDriver? ImrOpc { get; }
+ public AsrsOpcDriver? AsrsOpc { get; }
public RobotState ImrState { get; }
public RobotState AmrState { get; }
@@ -51,6 +52,7 @@ public sealed class RealDriverContext : IDriverContext
public RealDriverContext(
ImrVdaDriver imr, AmrVdaDriver amr, ImrOpcUaDriver imrOpc,
IConveyorDriver conveyor, IAsrsDriver asrs, IDobotDriver dobot,
+ AsrsOpcDriver asrsOpc,
IEnumerable states,
FlowService workflow,
FlowWithAsrs asrsFlow,
@@ -66,6 +68,7 @@ public sealed class RealDriverContext : IDriverContext
Imr = imr; Amr = amr; ImrOpc = imrOpc;
Conveyor = conveyor; Asrs = asrs; Dobot = dobot;
+ AsrsOpc = asrsOpc;
ImrState = stateList[0]; AmrState = stateList[1];
SystemCondition = systemState;
diff --git a/Lab505/Application/Contexts/SimDriverContext.cs b/Lab505/Application/Contexts/SimDriverContext.cs
index 221da78..863e866 100644
--- a/Lab505/Application/Contexts/SimDriverContext.cs
+++ b/Lab505/Application/Contexts/SimDriverContext.cs
@@ -35,6 +35,7 @@ public sealed class SimDriverContext : IDriverContext, IHostedService
public IAsrsDriver Asrs { get; }
public IDobotDriver Dobot { get; }
public ImrOpcUaDriver? ImrOpc { get; }
+ public AsrsOpcDriver? AsrsOpc => null;
public RobotState ImrState { get; }
public RobotState AmrState { get; }
diff --git a/Lab505/Application/Contexts/UserSimSession.cs b/Lab505/Application/Contexts/UserSimSession.cs
index 5edfff0..d8c523b 100644
--- a/Lab505/Application/Contexts/UserSimSession.cs
+++ b/Lab505/Application/Contexts/UserSimSession.cs
@@ -44,6 +44,7 @@ public sealed class UserSimSession : IDriverContext, IAsyncDisposable
public IAsrsDriver Asrs { get; }
public IDobotDriver Dobot { get; }
public ImrOpcUaDriver? ImrOpc => null; // no OPC UA per user
+ public AsrsOpcDriver? AsrsOpc => null; // ASRS OPC UA chỉ có trên real stack
public RobotState ImrState { get; }
public RobotState AmrState { get; }
@@ -264,6 +265,7 @@ public sealed class UserSimSession : IDriverContext, IAsyncDisposable
await caller.SendAsync(HubContracts.AmrStateEvent, BuildRobotDto(AmrState));
await caller.SendAsync(HubContracts.ConveyorStateEvent, BuildConveyorDto());
await caller.SendAsync(HubContracts.AsrsStateEvent, BuildAsrsDto());
+ await caller.SendAsync(HubContracts.AsrsOpcStateEvent, StateDtoFactory.BuildAsrsOpcDto(null));
await caller.SendAsync(HubContracts.WorkflowStateEvent, BuildWorkflowDto());
await caller.SendAsync(HubContracts.LockStateEvent, BuildLockDto());
await caller.SendAsync(HubContracts.SystemStateEvent, new SystemStateDto(true, false));
diff --git a/Lab505/Infrastructure/Drivers/Asrs/AsrsOpcDriver.cs b/Lab505/Infrastructure/Drivers/Asrs/AsrsOpcDriver.cs
new file mode 100644
index 0000000..8fb3ed2
--- /dev/null
+++ b/Lab505/Infrastructure/Drivers/Asrs/AsrsOpcDriver.cs
@@ -0,0 +1,279 @@
+using Lab505.Application.Services;
+using Lab505.Infrastructure.Protocols.OpcUa;
+using Lab505.Shared;
+using Opc.Ua;
+using StatusCodes = Opc.Ua.StatusCodes;
+
+namespace Lab505.Infrastructure.Drivers.Asrs;
+
+/// ASRS không nhận lệnh vì offline/chưa cấu hình (API trả 503).
+public class AsrsOpcUnavailableException(string message) : InvalidOperationException(message);
+
+///
+/// Điều khiển ASRS qua gateway OPC UA (AsrsOpcUaServer → Modbus → PLC).
+///
+/// Theo ASRS_OPC_UA_Interface.md, method của gateway chỉ trả kết quả khi PLC đã thực hiện xong
+/// (StatusCode = 0 ⇒ thành công, Occupied đã cập nhật). Driver:
+/// 1. Kiểm tra điều kiện trước khi gửi (online, Fault, trạng thái ô, tham số).
+/// KHÔNG chặn khi PLC Busy: PLC giữ Busy thêm 3s chờ lệnh kế tiếp để chạy nối luôn.
+/// 2. Gọi method và chờ kết quả (có thể > 60s), ném lỗi nếu StatusCode xấu.
+/// 3. Chờ ngắn để state poll của Lab505 thấy ô đã đổi (tránh kiểm tra lệnh kế tiếp trên state cũ).
+/// Mỗi thời điểm Lab505 chỉ gửi 1 lệnh; gửi khi đang bận → ném lỗi (không im lặng bỏ qua).
+/// Cancel token chỉ dừng việc CHỜ phía Lab505 — gateway không có lệnh dừng phần cứng (dùng E-Stop).
+///
+public sealed class AsrsOpcDriver(AsrsOpcState state, AsrsOpcOptions options, INotificationService notif)
+{
+ private readonly SemaphoreSlim _gate = new(1, 1);
+ private readonly OpcUaClient _ua = state.Client;
+
+ public AsrsOpcState State => state;
+
+ /// Lab505 đang thực thi lệnh (khác State.Busy — Busy của PLC).
+ public bool IsBusy => CurrentOp is not null;
+ public string? CurrentOp { get; private set; }
+ public string? LastError { get; private set; }
+
+ public event Action? OnOperationStateChanged;
+
+ // ═══════════════════════════════════════════════════════════════
+ // Guards — public để API kiểm tra trước và trả lỗi ngay cho client
+ // ═══════════════════════════════════════════════════════════════
+
+ public void RequireCanHome() => RequireReady("Home");
+
+ public void RequireCanRetrieve(int column, int shelf, int conveyor)
+ {
+ RequireSlot(column, shelf);
+ RequireConveyor(conveyor);
+ RequireReady("Retrieve");
+ if (state.IsOccupied(column, shelf) != true)
+ throw new InvalidOperationException($"Ô {column}.{shelf} đang trống — không có khay để lấy ra");
+ }
+
+ public void RequireCanStore(int column, int shelf, int conveyor)
+ {
+ RequireSlot(column, shelf);
+ RequireConveyor(conveyor);
+ RequireReady("Store");
+ if (state.IsOccupied(column, shelf) != false)
+ throw new InvalidOperationException($"Ô {column}.{shelf} đã có khay — không thể trả khay vào");
+ }
+
+ public void RequireCanStoreAny(int conveyor)
+ {
+ RequireConveyor(conveyor);
+ RequireReady("StoreAny");
+ if (!state.OccupiedSnapshot().Any(o => o == false))
+ throw new InvalidOperationException("Kho không còn ô trống");
+ }
+
+ public void RequireCanMove(int fromColumn, int fromShelf, int toColumn, int toShelf)
+ {
+ RequireSlot(fromColumn, fromShelf);
+ RequireSlot(toColumn, toShelf);
+ if (fromColumn == toColumn && fromShelf == toShelf)
+ throw new ArgumentException("Ô nguồn và ô đích trùng nhau");
+ RequireReady("Move");
+ if (state.IsOccupied(fromColumn, fromShelf) != true)
+ throw new InvalidOperationException($"Ô nguồn {fromColumn}.{fromShelf} đang trống");
+ if (state.IsOccupied(toColumn, toShelf) != false)
+ throw new InvalidOperationException($"Ô đích {toColumn}.{toShelf} đã có khay");
+ }
+
+ // ═══════════════════════════════════════════════════════════════
+ // Commands
+ // ═══════════════════════════════════════════════════════════════
+
+ /// Home toàn hệ thống.
+ public Task Home(CancellationToken ct = default)
+ => Run("Home", RequireCanHome,
+ n => (n.Home, []),
+ _ => s => s.Homed == true, ct);
+
+ /// Lấy khay ở ô (column, shelf) ra băng tải conveyor (1 = trái, 2 = phải).
+ public Task Retrieve(int column, int shelf, int conveyor, CancellationToken ct = default)
+ => Run($"Retrieve {column}.{shelf} → BT{conveyor}",
+ () => RequireCanRetrieve(column, shelf, conveyor),
+ n => (n.Retrieve, [(ushort)column, (ushort)shelf, (ushort)conveyor]),
+ _ => s => s.IsOccupied(column, shelf) == false, ct);
+
+ /// Trả khay từ băng tải conveyor (1 = trái, 2 = phải) vào ô (column, shelf).
+ public Task Store(int column, int shelf, int conveyor, CancellationToken ct = default)
+ => Run($"Store BT{conveyor} → {column}.{shelf}",
+ () => RequireCanStore(column, shelf, conveyor),
+ n => (n.Store, [(ushort)column, (ushort)shelf, (ushort)conveyor]),
+ _ => s => s.IsOccupied(column, shelf) == true, ct);
+
+ /// Trả khay từ băng tải vào ô trống đầu tiên (gateway chọn ô). Trả về ô đã chọn.
+ public async Task<(int Column, int Shelf)> StoreAny(int conveyor, CancellationToken ct = default)
+ {
+ var outputs = await Run($"StoreAny BT{conveyor}",
+ () => RequireCanStoreAny(conveyor),
+ n => (n.StoreAny, [(ushort)conveyor]),
+ outs =>
+ {
+ var (col, shelf) = ParseSlot(outs);
+ SetCurrentOp($"StoreAny BT{conveyor} → {col}.{shelf}");
+ return s => s.IsOccupied(col, shelf) == true;
+ }, ct);
+ return ParseSlot(outputs);
+ }
+
+ /// Chuyển khay từ ô nguồn sang ô đích trong kho.
+ public Task Move(int fromColumn, int fromShelf, int toColumn, int toShelf, CancellationToken ct = default)
+ => Run($"Move {fromColumn}.{fromShelf} → {toColumn}.{toShelf}",
+ () => RequireCanMove(fromColumn, fromShelf, toColumn, toShelf),
+ n => (n.Move,
+ [(ushort)fromColumn, (ushort)fromShelf, (ushort)toColumn, (ushort)toShelf]),
+ _ => s => s.IsOccupied(fromColumn, fromShelf) == false
+ && s.IsOccupied(toColumn, toShelf) == true, ct);
+
+ // ═══════════════════════════════════════════════════════════════
+ // Core
+ // ═══════════════════════════════════════════════════════════════
+
+ private async Task> Run(
+ string label,
+ Action validate,
+ Func request,
+ Func, Func> syncedFactory,
+ CancellationToken ct)
+ {
+ validate();
+ if (!await _gate.WaitAsync(0, ct))
+ throw new InvalidOperationException($"ASRS đang thực hiện '{CurrentOp}' — chờ lệnh hiện tại xong");
+
+ try
+ {
+ validate(); // kiểm tra lại sau khi giữ gate (state có thể vừa đổi)
+ SetCurrentOp(label);
+ LastError = null;
+
+ var nodes = state.Nodes
+ ?? throw new AsrsOpcUnavailableException("ASRS OPC UA chưa tìm được node trên gateway");
+ var (method, args) = request(nodes);
+ notif.Notify("ASRS", label, "info", "gửi lệnh OPC UA");
+ // Gateway chỉ trả về khi PLC đã xong (hoặc lỗi / Fault / timeout phía gateway)
+ var outputs = await _ua.CallCheckedAsync(AsrsNodeIds.MethodOwner, method, args, ct);
+ EnsureGood(label, outputs);
+
+ // Gateway đã xác nhận xong — chờ state poll của Lab505 bắt kịp. Hết giờ vẫn coi là thành công.
+ var synced = syncedFactory(outputs);
+ using var syncCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
+ syncCts.CancelAfter(options.StateSyncTimeoutMs);
+ try
+ {
+ await WaitUntil(synced, syncCts.Token);
+ }
+ catch (OperationCanceledException) when (!ct.IsCancellationRequested)
+ {
+ notif.Notify("ASRS", CurrentOp ?? label, "warning",
+ $"gateway báo xong nhưng trạng thái ô chưa cập nhật sau {options.StateSyncTimeoutMs} ms");
+ }
+
+ notif.Notify("ASRS", CurrentOp ?? label, "success", "hoàn thành");
+ return outputs;
+ }
+ catch (OperationCanceledException)
+ {
+ notif.Notify("ASRS", CurrentOp ?? label, "warning", "ngừng chờ (phần cứng không dừng — dùng E-Stop nếu cần)");
+ throw;
+ }
+ catch (Exception ex)
+ {
+ LastError = $"{CurrentOp ?? label}: {ex.Message}";
+ notif.Notify("ASRS", CurrentOp ?? label, "error", ex.Message);
+ throw;
+ }
+ finally
+ {
+ SetCurrentOp(null);
+ _gate.Release();
+ }
+ }
+
+ private async Task WaitUntil(Func cond, CancellationToken ct)
+ {
+ if (cond(state)) return;
+
+ var tcs = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
+ void Handler() { if (cond(state)) tcs.TrySetResult(); }
+
+ state.OnStatusChanged += Handler;
+ try
+ {
+ Handler(); // re-check sau khi subscribe — tránh lỡ event
+ await tcs.Task.WaitAsync(ct);
+ }
+ finally
+ {
+ state.OnStatusChanged -= Handler;
+ }
+ }
+
+ private static void EnsureGood(string label, IList