done
This commit is contained in:
1
.gitignore
vendored
1
.gitignore
vendored
@@ -2,3 +2,4 @@ bin/
|
||||
obj/
|
||||
.vs/
|
||||
*.user
|
||||
Lab505/certs/https.pfx
|
||||
|
||||
@@ -21,6 +21,14 @@
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (S.Available)
|
||||
{
|
||||
<div class="mt-1 mb-1">
|
||||
<MudButton FullWidth="true" Variant="Variant.Outlined" Color="Color.Error" Size="Size.Small"
|
||||
Disabled="@(!CanCancel)" OnClick="Cancel">Cancel</MudButton>
|
||||
</div>
|
||||
}
|
||||
|
||||
@if (!string.IsNullOrEmpty(S.LastError))
|
||||
{
|
||||
<MudText Typo="Typo.caption" Style="color:#e74c3c;display:block;">@S.LastError</MudText>
|
||||
@@ -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; }
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
|
||||
@@ -35,6 +35,36 @@ public sealed class AsrsOpcDriver(AsrsOpcState state, AsrsOpcOptions options, IN
|
||||
|
||||
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
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
@@ -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<object> 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",
|
||||
|
||||
@@ -20,6 +20,9 @@ public sealed class AsrsNodeMap
|
||||
public required NodeId StoreAny { get; init; }
|
||||
public required NodeId Move { get; init; }
|
||||
|
||||
/// <summary>Method Cancel() — null nếu gateway bản cũ chưa có.</summary>
|
||||
public NodeId? Cancel { get; init; }
|
||||
|
||||
/// <summary>Node đọc mỗi chu kỳ poll: [Homed, Ready, Busy, Fault, Occupied × 12].</summary>
|
||||
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, []);
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
{
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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://<IP máy chạy gateway>:4840/ASRS/ — để trống = tắt",
|
||||
|
||||
BIN
Lab505/auth.db
BIN
Lab505/auth.db
Binary file not shown.
Binary file not shown.
Binary file not shown.
Reference in New Issue
Block a user