diff --git a/.gitignore b/.gitignore index 547a964..2728a62 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ bin/ obj/ .vs/ *.user +Lab505/certs/https.pfx diff --git a/Lab505.Client/Pages/AsrsOpcPanel.razor b/Lab505.Client/Pages/AsrsOpcPanel.razor index 7434bb5..4bcb990 100644 --- a/Lab505.Client/Pages/AsrsOpcPanel.razor +++ b/Lab505.Client/Pages/AsrsOpcPanel.razor @@ -21,6 +21,14 @@ + @if (S.Available) + { +
+ Cancel +
+ } + @if (!string.IsNullOrEmpty(S.LastError)) { @S.LastError @@ -137,6 +145,9 @@ private bool CanCommand => State.CanControl && S.Available && S.Online && S.Fault != true && !S.DriverBusy; + // Cancel bấm được cả khi đang chạy / PLC Busy (lệnh có thể do client khác gửi) + private bool CanCancel => State.CanControl && S.Available && S.Online; + 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; @@ -163,6 +174,7 @@ private Task StoreAny() => Cmd.AsrsOpcStoreAnyAsync(_conveyor); private Task Home() => Cmd.AsrsOpcHomeAsync(); + private Task Cancel() => Cmd.AsrsOpcCancelAsync(); private void ClearSel() { _from = null; _to = null; } } diff --git a/Lab505.Client/Services/CommandService.cs b/Lab505.Client/Services/CommandService.cs index cf53161..ec4765d 100644 --- a/Lab505.Client/Services/CommandService.cs +++ b/Lab505.Client/Services/CommandService.cs @@ -170,6 +170,9 @@ public class CommandService } // ── ASRS qua OPC UA (gateway) ───────────────────────────────────────── + public Task AsrsOpcCancelAsync(CancellationToken ct = default) + => PostAsrsOpcAsync("Cancel", null, "/api/asrs/opc/cancel", null, ct); + public Task AsrsOpcHomeAsync(CancellationToken ct = default) => PostAsrsOpcAsync("Home", null, "/api/asrs/opc/home", null, ct); diff --git a/Lab505/Infrastructure/Drivers/Asrs/AsrsOpcDriver.cs b/Lab505/Infrastructure/Drivers/Asrs/AsrsOpcDriver.cs index 8fb3ed2..239ee1e 100644 --- a/Lab505/Infrastructure/Drivers/Asrs/AsrsOpcDriver.cs +++ b/Lab505/Infrastructure/Drivers/Asrs/AsrsOpcDriver.cs @@ -35,6 +35,36 @@ public sealed class AsrsOpcDriver(AsrsOpcState state, AsrsOpcOptions options, IN public event Action? OnOperationStateChanged; + private CancellationTokenSource? _opCts; + + /// + /// 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). + /// + 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 // ═══════════════════════════════════════════════════════════════ @@ -143,6 +173,9 @@ public sealed class AsrsOpcDriver(AsrsOpcState state, AsrsOpcOptions options, IN 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) @@ -174,10 +207,11 @@ public sealed class AsrsOpcDriver(AsrsOpcState state, AsrsOpcOptions options, IN notif.Notify("ASRS", CurrentOp ?? label, "success", "hoàn thành"); return outputs; } - catch (OperationCanceledException) + catch (Exception ex) when (ex is OperationCanceledException || ct.IsCancellationRequested) { - 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; + // 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) { @@ -187,6 +221,7 @@ public sealed class AsrsOpcDriver(AsrsOpcState state, AsrsOpcOptions options, IN } finally { + _opCts = null; SetCurrentOp(null); _gate.Release(); } @@ -211,6 +246,13 @@ public sealed class AsrsOpcDriver(AsrsOpcState state, AsrsOpcOptions options, IN } } + private static uint? ToStatus(object? v) => v switch + { + int i => unchecked((uint)i), + uint u => u, + _ => null + }; + private static void EnsureGood(string label, IList outputs) { // Spec: StatusCode là Int32 (0 = Good); mã Bad giữ bit pattern của OPC UA StatusCode. @@ -228,6 +270,7 @@ public sealed class AsrsOpcDriver(AsrsOpcState state, AsrsOpcOptions options, IN 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", diff --git a/Lab505/Infrastructure/Protocols/OpcUa/AsrsNodeIds.cs b/Lab505/Infrastructure/Protocols/OpcUa/AsrsNodeIds.cs index 902b00d..4998e34 100644 --- a/Lab505/Infrastructure/Protocols/OpcUa/AsrsNodeIds.cs +++ b/Lab505/Infrastructure/Protocols/OpcUa/AsrsNodeIds.cs @@ -20,6 +20,9 @@ public sealed class AsrsNodeMap public required NodeId StoreAny { get; init; } public required NodeId Move { get; init; } + /// Method Cancel() — null nếu gateway bản cũ chưa có. + public NodeId? Cancel { get; init; } + /// Node đọc mỗi chu kỳ poll: [Homed, Ready, Busy, Fault, Occupied × 12]. public NodeId[] StateNodes() => [Homed, Ready, Busy, Fault, .. Occupied]; } @@ -70,6 +73,9 @@ public static class AsrsNodeIds paths.Add([new QualifiedName(slot, ns), new QualifiedName("Occupied", ns)]); } + // Node tuỳ chọn (gateway bản cũ có thể chưa có) — đặt cuối, không tính vào "thiếu" + paths.Add([new QualifiedName("Cancel", ns)]); + var ids = await ua.TranslateBrowsePathsAsync(ObjectIds.ObjectsFolder, paths, ct); var missing = labels.Where((_, i) => ids[i] is null).ToArray(); @@ -88,7 +94,8 @@ public static class AsrsNodeIds Store = Id("Store"), StoreAny = Id("StoreAny"), Move = Id("Move"), - Occupied = ids.Skip(RootNames.Length).Select(id => id!).ToArray() + Occupied = ids.Skip(RootNames.Length).Take(AsrsOpcLayout.SlotCount).Select(id => id!).ToArray(), + Cancel = ids[^1] }; return (map, []); } diff --git a/Lab505/Infrastructure/Protocols/OpcUa/OpcUaClient.cs b/Lab505/Infrastructure/Protocols/OpcUa/OpcUaClient.cs index 034b5c8..00166ca 100644 --- a/Lab505/Infrastructure/Protocols/OpcUa/OpcUaClient.cs +++ b/Lab505/Infrastructure/Protocols/OpcUa/OpcUaClient.cs @@ -64,7 +64,11 @@ public class OpcUaClient(string EndpointUrl, string configSection, ILogger logge _clientCts?.Cancel(); if (_connectLoopTask != null) - await _connectLoopTask; + { + // ConnectLoop kết thúc bằng TaskCanceledException (Task.Delay bị huỷ) — là dừng bình thường + try { await _connectLoopTask; } + catch (OperationCanceledException) { } + } if (session != null) { diff --git a/Lab505/Presentation/Api/RobotApiExtensions.cs b/Lab505/Presentation/Api/RobotApiExtensions.cs index e47cbe9..548e332 100644 --- a/Lab505/Presentation/Api/RobotApiExtensions.cs +++ b/Lab505/Presentation/Api/RobotApiExtensions.cs @@ -588,6 +588,20 @@ public static class RobotApiExtensions opc.MapGet("/status", (UserContextResolver res, HttpContext ctx) => Results.Ok(StateDtoFactory.BuildAsrsOpcDto(res.Resolve(ctx).AsrsOpc))); + // Cancel: không cần ASRS rảnh — huỷ lệnh đang chạy (gateway ngừng chờ + hạ coil trigger) + opc.MapPost("/cancel", async (UserContextResolver res, HttpContext ctx) => + { + if (GuardDeviceOp(res, ctx, DeviceGroup.C2Asrs, out var stack) is { } err) return err; + if (stack.AsrsOpc is not { } driver) + return Results.Json(new { error = "ASRS OPC UA chỉ có trên real stack" }, statusCode: 503); + try + { + await driver.CancelAsync(ctx.RequestAborted); + return Results.Ok(); + } + catch (Exception ex) { return Results.Json(new { error = ex.Message }, statusCode: 502); } + }); + opc.MapPost("/home", (UserContextResolver res, HttpContext ctx, OperationTracker tracker) => StartAsrsOpc(res, ctx, tracker, d => d.RequireCanHome(), diff --git a/Lab505/appsettings.json b/Lab505/appsettings.json index dbf136f..dad9bce 100644 --- a/Lab505/appsettings.json +++ b/Lab505/appsettings.json @@ -65,7 +65,7 @@ }, { "Name": "ASRS", - "EndpointUrl": "opc.tcp://192.168.111.50:4840/ASRS/", + "EndpointUrl": "opc.tcp://192.168.111.228:4840/ASRS/", "ConfigSection": "OpcUaClient", "KeepAliveIntervalMs": 1000, "Description": "ASRS OPC UA gateway (AsrsOpcUaServer). Điền opc.tcp://:4840/ASRS/ — để trống = tắt", diff --git a/Lab505/auth.db b/Lab505/auth.db index 0409c62..314efc4 100644 Binary files a/Lab505/auth.db and b/Lab505/auth.db differ diff --git a/Lab505/auth.db-shm b/Lab505/auth.db-shm deleted file mode 100644 index a7d1283..0000000 Binary files a/Lab505/auth.db-shm and /dev/null differ diff --git a/Lab505/auth.db-wal b/Lab505/auth.db-wal deleted file mode 100644 index a5da8b5..0000000 Binary files a/Lab505/auth.db-wal and /dev/null differ