323 lines
15 KiB
C#
323 lines
15 KiB
C#
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;
|
|
|
|
/// <summary>ASRS không nhận lệnh vì offline/chưa cấu hình (API trả 503).</summary>
|
|
public class AsrsOpcUnavailableException(string message) : InvalidOperationException(message);
|
|
|
|
/// <summary>
|
|
/// Đ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).
|
|
/// </summary>
|
|
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;
|
|
|
|
/// <summary>Lab505 đang thực thi lệnh (khác State.Busy — Busy của PLC).</summary>
|
|
public bool IsBusy => CurrentOp is not null;
|
|
public string? CurrentOp { get; private set; }
|
|
public string? LastError { get; private set; }
|
|
|
|
public event Action? OnOperationStateChanged;
|
|
|
|
private CancellationTokenSource? _opCts;
|
|
|
|
/// <summary>
|
|
/// Huỷ lệnh: gọi method Cancel() của gateway (gateway ngừng chờ + hạ coil trigger),
|
|
/// rồi ngừng chờ phía Lab505. Gọi được cả khi lệnh do client khác gửi (vd RoboLab).
|
|
/// </summary>
|
|
public async Task CancelAsync(CancellationToken ct = default)
|
|
{
|
|
string? gatewayError = null;
|
|
if (state.Nodes?.Cancel is { } cancelNode)
|
|
{
|
|
try
|
|
{
|
|
var outputs = await _ua.CallCheckedAsync(AsrsNodeIds.MethodOwner, cancelNode, [], ct);
|
|
if (outputs.Count > 0 && ToStatus(outputs[0]) is { } code && !StatusCode.IsGood(code))
|
|
gatewayError = $"gateway báo lỗi khi huỷ: {StatusCode.LookupSymbolicId(code)}";
|
|
}
|
|
catch (Exception ex) { gatewayError = $"không gọi được Cancel trên gateway: {ex.Message}"; }
|
|
}
|
|
else
|
|
{
|
|
gatewayError = "gateway chưa có method Cancel — chỉ ngừng chờ phía Lab505";
|
|
}
|
|
|
|
_opCts?.Cancel();
|
|
notif.Notify("ASRS", "Cancel", gatewayError is null ? "warning" : "error", gatewayError ?? "đã huỷ lệnh");
|
|
if (gatewayError is not null && state.Nodes?.Cancel is not null)
|
|
throw new InvalidOperationException(gatewayError);
|
|
}
|
|
|
|
// ═══════════════════════════════════════════════════════════════
|
|
// 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
|
|
// ═══════════════════════════════════════════════════════════════
|
|
|
|
/// <summary>Home toàn hệ thống.</summary>
|
|
public Task Home(CancellationToken ct = default)
|
|
=> Run("Home", RequireCanHome,
|
|
n => (n.Home, []),
|
|
_ => s => s.Homed == true, ct);
|
|
|
|
/// <summary>Lấy khay ở ô (column, shelf) ra băng tải conveyor (1 = trái, 2 = phải).</summary>
|
|
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);
|
|
|
|
/// <summary>Trả khay từ băng tải conveyor (1 = trái, 2 = phải) vào ô (column, shelf).</summary>
|
|
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);
|
|
|
|
/// <summary>Trả khay từ băng tải vào ô trống đầu tiên (gateway chọn ô). Trả về ô đã chọn.</summary>
|
|
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);
|
|
}
|
|
|
|
/// <summary>Chuyển khay từ ô nguồn sang ô đích trong kho.</summary>
|
|
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<IList<object>> Run(
|
|
string label,
|
|
Action validate,
|
|
Func<AsrsNodeMap, (NodeId Method, object[] Args)> request,
|
|
Func<IList<object>, Func<AsrsOpcState, bool>> 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");
|
|
|
|
using var opCts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
_opCts = opCts;
|
|
ct = opCts.Token;
|
|
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 (Exception ex) when (ex is OperationCanceledException || ct.IsCancellationRequested)
|
|
{
|
|
// Cancel: client OPC UA bỏ lời gọi đang chờ (BadRequestInterrupted) — báo gọn là "đã huỷ"
|
|
LastError = $"{CurrentOp ?? label}: đã huỷ (Cancel)";
|
|
throw new OperationCanceledException(LastError, ex, ct);
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
LastError = $"{CurrentOp ?? label}: {ex.Message}";
|
|
notif.Notify("ASRS", CurrentOp ?? label, "error", ex.Message);
|
|
throw;
|
|
}
|
|
finally
|
|
{
|
|
_opCts = null;
|
|
SetCurrentOp(null);
|
|
_gate.Release();
|
|
}
|
|
}
|
|
|
|
private async Task WaitUntil(Func<AsrsOpcState, bool> 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 uint? ToStatus(object? v) => v switch
|
|
{
|
|
int i => unchecked((uint)i),
|
|
uint u => u,
|
|
_ => null
|
|
};
|
|
|
|
private static void EnsureGood(string label, IList<object> outputs)
|
|
{
|
|
// Spec: StatusCode là Int32 (0 = Good); mã Bad giữ bit pattern của OPC UA StatusCode.
|
|
// Vẫn nhận UInt32 để tương thích gateway bản cũ.
|
|
uint code = outputs.Count == 0 ? 0xFFFFFFFF : outputs[0] switch
|
|
{
|
|
int i => unchecked((uint)i),
|
|
uint u => u,
|
|
_ => 0xFFFFFFFF
|
|
};
|
|
if (code == 0xFFFFFFFF)
|
|
throw new InvalidOperationException($"{label}: gateway trả kết quả không hợp lệ");
|
|
if (StatusCode.IsGood(code)) return;
|
|
|
|
string reason = code switch
|
|
{
|
|
StatusCodes.BadNotExecutable => "ASRS Fault (E-Stop / Safety)",
|
|
StatusCodes.BadRequestCancelledByClient => "đã huỷ (Cancel)",
|
|
StatusCodes.BadTimeout => "PLC chưa thực hiện xong trong thời gian chờ của gateway",
|
|
StatusCodes.BadCommunicationError => "gateway không ghi được lệnh xuống PLC (Modbus)",
|
|
StatusCodes.BadOutOfRange => "tham số ngoài phạm vi",
|
|
StatusCodes.BadResourceUnavailable => "kho không còn ô trống",
|
|
StatusCodes.BadNotFound => "ô nguồn đang trống",
|
|
StatusCodes.BadEntryExists => "ô đích đã có khay",
|
|
_ => StatusCode.LookupSymbolicId(code)
|
|
};
|
|
throw new InvalidOperationException($"{label}: gateway từ chối — {reason}");
|
|
}
|
|
|
|
private static (int Column, int Shelf) ParseSlot(IList<object> outputs)
|
|
{
|
|
if (outputs.Count < 3 || outputs[1] is not ushort col || outputs[2] is not ushort shelf || col == 0 || shelf == 0)
|
|
throw new InvalidOperationException("StoreAny: gateway không trả về ô hợp lệ");
|
|
return (col, shelf);
|
|
}
|
|
|
|
private void RequireReady(string op)
|
|
{
|
|
if (!options.IsConfigured)
|
|
throw new AsrsOpcUnavailableException("ASRS OPC UA chưa cấu hình EndpointUrl");
|
|
if (!state.IsOnline)
|
|
throw new AsrsOpcUnavailableException($"ASRS OPC UA offline — không thể {op}");
|
|
if (IsBusy)
|
|
throw new InvalidOperationException($"ASRS đang thực hiện '{CurrentOp}' — chờ lệnh hiện tại xong");
|
|
if (state.Fault == true)
|
|
throw new InvalidOperationException("ASRS đang Fault (E-Stop / Safety) — không thể gửi lệnh");
|
|
}
|
|
|
|
private static void RequireSlot(int column, int shelf)
|
|
{
|
|
if (column < 1 || column > AsrsOpcLayout.Columns || shelf < 1 || shelf > AsrsOpcLayout.Shelves)
|
|
throw new ArgumentException(
|
|
$"Ô {column}.{shelf} không hợp lệ — cột 1..{AsrsOpcLayout.Columns}, tầng 1..{AsrsOpcLayout.Shelves}");
|
|
}
|
|
|
|
private static void RequireConveyor(int conveyor)
|
|
{
|
|
if (conveyor is not (1 or 2))
|
|
throw new ArgumentException("Băng tải phải là 1 (trái) hoặc 2 (phải)");
|
|
}
|
|
|
|
private void SetCurrentOp(string? label)
|
|
{
|
|
CurrentOp = label;
|
|
OnOperationStateChanged?.Invoke();
|
|
}
|
|
}
|