first commit
This commit is contained in:
4
.gitignore
vendored
Normal file
4
.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
bin/
|
||||
obj/
|
||||
.vs/
|
||||
*.user
|
||||
184
Lab505.Client/Pages/AsrsOpcPanel.razor
Normal file
184
Lab505.Client/Pages/AsrsOpcPanel.razor
Normal file
@@ -0,0 +1,184 @@
|
||||
@implements IAsyncDisposable
|
||||
|
||||
<MudPaper Elevation="0" Class="pa-2" Style="background:transparent;">
|
||||
|
||||
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center"
|
||||
Style="cursor:pointer" @onclick="Toggle">
|
||||
<MudText Typo="Typo.subtitle1">ASRS · OPC UA</MudText>
|
||||
<MudIcon Icon="@(_expanded ? Icons.Material.Filled.ExpandMore : Icons.Material.Filled.ExpandLess)" Size="Size.Small" />
|
||||
</MudStack>
|
||||
|
||||
<div class="status-row mt-2">
|
||||
<MudIcon Icon="@Icons.Material.Filled.Circle" Size="Size.Small" Color="@StatusColor" />
|
||||
<div>
|
||||
<MudText Typo="Typo.caption">@StatusText</MudText>
|
||||
@if (S.Available && S.Online)
|
||||
{
|
||||
<MudText Typo="Typo.caption" Style="color:#9a9a9a;">
|
||||
Homed: @Fmt(S.Homed) | Busy: @Fmt(S.Busy) | Fault: @Fmt(S.Fault)
|
||||
</MudText>
|
||||
}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@if (!string.IsNullOrEmpty(S.LastError))
|
||||
{
|
||||
<MudText Typo="Typo.caption" Style="color:#e74c3c;display:block;">@S.LastError</MudText>
|
||||
}
|
||||
|
||||
@if (_expanded && S.Available)
|
||||
{
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">
|
||||
Kho (cột × tầng) — chọn ô@(_from is null ? "" : $": {Name(_from.Value)}")@(_to is null ? "" : $" → {Name(_to.Value)}")
|
||||
</MudText>
|
||||
<div class="slot-grid">
|
||||
@for (int shelf = AsrsOpcLayout.Shelves; shelf >= 1; shelf--)
|
||||
{
|
||||
<span class="slot-row-label">T@(shelf)</span>
|
||||
@for (int col = 1; col <= AsrsOpcLayout.Columns; col++)
|
||||
{
|
||||
var cell = (col, shelf);
|
||||
<button class="@CellClass(cell)" disabled="@(!S.Online)" @onclick="() => Pick(cell)">
|
||||
@col.@shelf
|
||||
</button>
|
||||
}
|
||||
}
|
||||
</div>
|
||||
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">Băng tải</MudText>
|
||||
<div class="op-grid-2">
|
||||
<MudButton Variant="@(_conveyor == 1 ? Variant.Filled : Variant.Outlined)" Color="Color.Primary" Size="Size.Small"
|
||||
OnClick="() => _conveyor = 1">BT1 · Trái</MudButton>
|
||||
<MudButton Variant="@(_conveyor == 2 ? Variant.Filled : Variant.Outlined)" Color="Color.Primary" Size="Size.Small"
|
||||
OnClick="() => _conveyor = 2">BT2 · Phải</MudButton>
|
||||
</div>
|
||||
|
||||
<MudText Typo="Typo.caption" Class="sec-title mt-2">Lệnh</MudText>
|
||||
<div class="op-grid">
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanRetrieve)" OnClick="Retrieve">Retrieve</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanStore)" OnClick="Store">Store</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanMove)" OnClick="Move">Move</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanStoreAny)" OnClick="StoreAny">StoreAny</MudButton>
|
||||
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanCommand)" OnClick="Home"
|
||||
Color="Color.Primary" Style="grid-column:span 2;">Home</MudButton>
|
||||
</div>
|
||||
}
|
||||
|
||||
</MudPaper>
|
||||
|
||||
@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;
|
||||
}
|
||||
|
||||
/// <summary>Click 1 = ô chính (Retrieve/Store/nguồn Move). Click 2 ô khác = ô đích Move. Click lại = bỏ chọn.</summary>
|
||||
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; }
|
||||
}
|
||||
|
||||
<style>
|
||||
.status-row { display:flex; align-items:center; gap:8px; margin-bottom:4px; }
|
||||
.sec-title { display:block; color:#9CA3AF; margin-bottom:4px; }
|
||||
.op-grid { display:grid; grid-template-columns:repeat(3, 1fr); gap:5px; }
|
||||
.op-grid-2 { display:grid; grid-template-columns:repeat(2, 1fr); gap:5px; }
|
||||
.slot-grid { display:grid; grid-template-columns:28px repeat(3, 1fr); gap:4px; align-items:center; }
|
||||
.slot-row-label { color:#9CA3AF; font-size:11px; text-align:center; }
|
||||
.slot { height:26px; border-radius:4px; border:1px solid rgba(255,255,255,0.18);
|
||||
background:transparent; color:#9a9a9a; font-size:11px; cursor:pointer; }
|
||||
.slot.full { background:rgba(46,204,113,0.25); border-color:rgba(46,204,113,0.6); color:#e6e6e6; }
|
||||
.slot.unknown { opacity:0.4; }
|
||||
.slot:disabled { cursor:default; }
|
||||
.slot.sel-from { outline:2px solid #4a9eff; outline-offset:1px; }
|
||||
.slot.sel-to { outline:2px dashed #f39c12; outline-offset:1px; }
|
||||
</style>
|
||||
@@ -92,7 +92,7 @@
|
||||
<div id="p-imr" class="panel-card"><ImrPanel /></div>
|
||||
<div id="p-amr" class="panel-card"><AmrPanel /></div>
|
||||
<div id="p-dobot" class="panel-card"><DobotPanel /></div>
|
||||
<div id="p-asrs" class="panel-card"><AsrsPanel /></div>
|
||||
<div id="p-asrs" class="panel-card"><AsrsOpcPanel /></div>
|
||||
</div>
|
||||
|
||||
@code {
|
||||
|
||||
@@ -4,12 +4,12 @@
|
||||
@RobotRow("IMR", State.Imr)
|
||||
@RobotRow("AMR", State.Amr)
|
||||
<div class="ias-row">
|
||||
<MudChip T="string" Size="Size.Small" Color="@(!State.Asrs.IsOffline ? Color.Success : Color.Default)"
|
||||
<MudChip T="string" Size="Size.Small" Color="@(State.AsrsOpc.Online ? Color.Success : Color.Default)"
|
||||
Variant="Variant.Text" Style="height:22px;font-size:11px;margin:0;flex-shrink:0;">ASRS</MudChip>
|
||||
<MudChip T="string" Size="Size.Small"
|
||||
Color="@(State.Asrs.SAFETY_MODE == true ? Color.Success : Color.Default)"
|
||||
Variant="@(State.Asrs.SAFETY_MODE == true ? Variant.Filled : Variant.Outlined)"
|
||||
Style="height:22px;font-size:11px;margin:0;flex-shrink:0;">Safety</MudChip>
|
||||
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")</MudChip>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -26,13 +26,13 @@
|
||||
|
||||
<MudDivider Class="mt-2 mb-1" />
|
||||
|
||||
@* ── ASRS grid ── *@
|
||||
@* ── ASRS grid — Slot.{cột}.{tầng}.Occupied từ gateway OPC UA, tầng cao nhất ở trên ── *@
|
||||
<div style="display:grid;grid-template-columns:repeat(3,1fr);gap:4px;">
|
||||
@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;
|
||||
<MudChip T="string" Size="Size.Small"
|
||||
Color="@(on ? Color.Info : Color.Default)"
|
||||
Variant="@(on ? Variant.Filled : Variant.Outlined)"
|
||||
@@ -63,13 +63,13 @@
|
||||
protected override async Task OnInitializedAsync()
|
||||
{
|
||||
await State.StartAsync();
|
||||
State.AsrsChanged += Refresh;
|
||||
State.AsrsOpcChanged += Refresh;
|
||||
State.WorkflowChanged += Refresh;
|
||||
}
|
||||
|
||||
public ValueTask DisposeAsync()
|
||||
{
|
||||
State.AsrsChanged -= Refresh;
|
||||
State.AsrsOpcChanged -= Refresh;
|
||||
State.WorkflowChanged -= Refresh;
|
||||
return ValueTask.CompletedTask;
|
||||
}
|
||||
@@ -94,12 +94,13 @@
|
||||
!string.IsNullOrEmpty(State.Workflow.LastError) ? "color:#e74c3c;" :
|
||||
State.Workflow.IsRunning ? "color:#4a9eff;" : "color:#9CA3AF;";
|
||||
|
||||
private (string RowLabel, (string Label, bool? Val)[] Cells)[] AsrsRows => 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();
|
||||
|
||||
}
|
||||
|
||||
@@ -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<ApiErrorBody>(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)
|
||||
{
|
||||
|
||||
@@ -279,6 +279,16 @@ public class ScriptLogService : IDisposable
|
||||
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()
|
||||
|
||||
@@ -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<AsrsOpcPushDto>(HubContracts.AsrsOpcStateEvent, dto =>
|
||||
{
|
||||
AsrsOpc = dto;
|
||||
AsrsOpcChanged?.Invoke();
|
||||
});
|
||||
|
||||
_hub.On<WorkflowStateDto>(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<string>(), 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);
|
||||
}
|
||||
|
||||
31
Lab505.Shared/AsrsOpcPushDto.cs
Normal file
31
Lab505.Shared/AsrsOpcPushDto.cs
Normal file
@@ -0,0 +1,31 @@
|
||||
namespace Lab505.Shared;
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 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).
|
||||
/// </summary>
|
||||
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
|
||||
);
|
||||
@@ -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";
|
||||
|
||||
|
||||
@@ -32,6 +32,9 @@ public interface IDriverContext
|
||||
/// <summary>null đối với sim stack (không có OPC UA riêng cho sim IMR).</summary>
|
||||
ImrOpcUaDriver? ImrOpc { get; }
|
||||
|
||||
/// <summary>ASRS qua gateway OPC UA — null đối với sim stack.</summary>
|
||||
AsrsOpcDriver? AsrsOpc { get; }
|
||||
|
||||
// ── State ─────────────────────────────────────────────────────────────
|
||||
RobotState ImrState { get; }
|
||||
RobotState AmrState { get; }
|
||||
|
||||
@@ -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<RobotState> 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;
|
||||
|
||||
|
||||
@@ -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; }
|
||||
|
||||
@@ -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));
|
||||
|
||||
279
Lab505/Infrastructure/Drivers/Asrs/AsrsOpcDriver.cs
Normal file
279
Lab505/Infrastructure/Drivers/Asrs/AsrsOpcDriver.cs
Normal file
@@ -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;
|
||||
|
||||
/// <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;
|
||||
|
||||
// ═══════════════════════════════════════════════════════════════
|
||||
// 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");
|
||||
|
||||
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<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 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.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();
|
||||
}
|
||||
}
|
||||
198
Lab505/Infrastructure/Drivers/Asrs/AsrsOpcState.cs
Normal file
198
Lab505/Infrastructure/Drivers/Asrs/AsrsOpcState.cs
Normal file
@@ -0,0 +1,198 @@
|
||||
using Lab505.Application.Services;
|
||||
using Lab505.Infrastructure.Protocols.OpcUa;
|
||||
using Lab505.Shared;
|
||||
|
||||
namespace Lab505.Infrastructure.Drivers.Asrs;
|
||||
|
||||
/// <summary>
|
||||
/// Cấu hình client OPC UA tới gateway ASRS — đọc từ phần tử Name="ASRS"
|
||||
/// trong Infrastructure:OpcUa:Clients (appsettings.json).
|
||||
/// </summary>
|
||||
public sealed class AsrsOpcOptions
|
||||
{
|
||||
public string EndpointUrl { get; set; } = "";
|
||||
public string ConfigSection { get; set; } = "OpcUaClient";
|
||||
public int KeepAliveIntervalMs { get; set; } = 1000;
|
||||
public int PollIntervalMs { get; set; } = 300;
|
||||
|
||||
/// <summary>
|
||||
/// Sau khi gateway trả Good (PLC đã xong), chờ tối đa khoảng này để state poll của Lab505 thấy ô đổi.
|
||||
/// Thời gian chờ chính lệnh do gateway quyết định (METHOD_TIMEOUT_SECONDS) — OperationTimeout
|
||||
/// trong OpcUaClient.Config.xml (600s) phải lớn hơn giá trị đó.
|
||||
/// </summary>
|
||||
public int StateSyncTimeoutMs { get; set; } = 5_000;
|
||||
|
||||
public bool IsConfigured => !string.IsNullOrWhiteSpace(EndpointUrl);
|
||||
|
||||
public static AsrsOpcOptions From(IConfiguration config)
|
||||
{
|
||||
var opt = new AsrsOpcOptions();
|
||||
var section = config.GetSection("Infrastructure:OpcUa:Clients").GetChildren()
|
||||
.FirstOrDefault(c => string.Equals(c["Name"], "ASRS", StringComparison.OrdinalIgnoreCase));
|
||||
section?.Bind(opt);
|
||||
return opt;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Poll state ASRS từ gateway OPC UA (Homed/Ready/Busy/Fault + 12 ô Occupied).
|
||||
/// Sở hữu OpcUaClient riêng của ASRS: start khi host start, stop khi host stop.
|
||||
/// </summary>
|
||||
public sealed class AsrsOpcState(
|
||||
OpcUaClient ua, AsrsOpcOptions options,
|
||||
ILogger<AsrsOpcState> logger, INotificationService? notif = null) : BackgroundService
|
||||
{
|
||||
private readonly bool?[] _occupied = new bool?[AsrsOpcLayout.SlotCount];
|
||||
private string? _lastWarning;
|
||||
|
||||
// Node tìm theo BrowseName — tìm lại khi kết nối lại hoặc namespace index đổi
|
||||
private volatile AsrsNodeMap? _nodes;
|
||||
private int _nodesNs = -1;
|
||||
|
||||
public OpcUaClient Client => ua;
|
||||
|
||||
public bool IsOnline { get; private set; }
|
||||
public bool? Homed { get; private set; }
|
||||
public bool? Ready { get; private set; }
|
||||
public bool? Busy { get; private set; }
|
||||
public bool? Fault { get; private set; }
|
||||
|
||||
/// <summary>null = chưa đọc được (offline).</summary>
|
||||
public bool? IsOccupied(int column, int shelf) => _occupied[AsrsOpcLayout.SlotIndex(column, shelf)];
|
||||
|
||||
public bool?[] OccupiedSnapshot() => (bool?[])_occupied.Clone();
|
||||
|
||||
/// <summary>NodeId của gateway trên session hiện tại (null = chưa kết nối / chưa tìm được).</summary>
|
||||
public AsrsNodeMap? Nodes => _nodes;
|
||||
|
||||
public event Action? OnStatusChanged;
|
||||
|
||||
protected override async Task ExecuteAsync(CancellationToken token)
|
||||
{
|
||||
if (!options.IsConfigured)
|
||||
{
|
||||
logger.LogWarning("ASRS OPC UA: chưa cấu hình EndpointUrl (Infrastructure:OpcUa:Clients[Name=ASRS]) — bỏ qua");
|
||||
return;
|
||||
}
|
||||
|
||||
ua.ConnectChanged += _ => _nodes = null;
|
||||
|
||||
try
|
||||
{
|
||||
await ua.Start();
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogError(ex, "ASRS OPC UA: không khởi động được client");
|
||||
return;
|
||||
}
|
||||
|
||||
while (!token.IsCancellationRequested)
|
||||
{
|
||||
try
|
||||
{
|
||||
await PollAsync(token);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
logger.LogDebug(ex, "ASRS OPC UA poll lỗi");
|
||||
MarkOffline();
|
||||
}
|
||||
|
||||
try { await Task.Delay(options.PollIntervalMs, token); }
|
||||
catch (OperationCanceledException) { break; }
|
||||
}
|
||||
}
|
||||
|
||||
public override async Task StopAsync(CancellationToken cancellationToken)
|
||||
{
|
||||
await base.StopAsync(cancellationToken);
|
||||
if (options.IsConfigured)
|
||||
await ua.Stop();
|
||||
}
|
||||
|
||||
private async Task PollAsync(CancellationToken token)
|
||||
{
|
||||
if (!ua.IsConnected)
|
||||
{
|
||||
MarkOffline();
|
||||
return;
|
||||
}
|
||||
|
||||
int ns = ua.GetNamespaceIndex(AsrsNodeIds.NamespaceUri);
|
||||
if (ns < 0)
|
||||
{
|
||||
Warn($"Server {options.EndpointUrl} không có namespace {AsrsNodeIds.NamespaceUri} — sai endpoint?");
|
||||
MarkOffline();
|
||||
return;
|
||||
}
|
||||
|
||||
var nodes = _nodes;
|
||||
if (nodes is null || _nodesNs != ns)
|
||||
{
|
||||
var (map, missing) = await AsrsNodeIds.ResolveAsync(ua, (ushort)ns, token);
|
||||
if (map is null)
|
||||
{
|
||||
Warn($"Gateway thiếu node: {string.Join(", ", missing)} — không khớp ASRS_OPC_UA_Fix.md?");
|
||||
MarkOffline();
|
||||
return;
|
||||
}
|
||||
_nodes = nodes = map;
|
||||
_nodesNs = ns;
|
||||
logger.LogInformation("ASRS OPC UA: đã tìm được {Count} node theo BrowseName (ns={Ns})",
|
||||
map.StateNodes().Length + 5, ns);
|
||||
}
|
||||
_lastWarning = null;
|
||||
|
||||
var values = await ua.ReadManyAsync(nodes.StateNodes());
|
||||
if (values.All(v => v is null))
|
||||
{
|
||||
MarkOffline();
|
||||
return;
|
||||
}
|
||||
|
||||
bool changed = false;
|
||||
if (!IsOnline) { IsOnline = true; changed = true; }
|
||||
|
||||
changed |= Upd(() => Homed, v => Homed = v, ToBool(values[0]));
|
||||
changed |= Upd(() => Ready, v => Ready = v, ToBool(values[1]));
|
||||
changed |= Upd(() => Busy, v => Busy = v, ToBool(values[2]));
|
||||
changed |= Upd(() => Fault, v => Fault = v, ToBool(values[3]));
|
||||
|
||||
for (int i = 0; i < AsrsOpcLayout.SlotCount; i++)
|
||||
{
|
||||
var v = ToBool(values[4 + i]);
|
||||
if (_occupied[i] != v) { _occupied[i] = v; changed = true; }
|
||||
}
|
||||
|
||||
if (changed) OnStatusChanged?.Invoke();
|
||||
}
|
||||
|
||||
private void MarkOffline()
|
||||
{
|
||||
if (!IsOnline && Homed is null) return;
|
||||
|
||||
IsOnline = false;
|
||||
Homed = Ready = Busy = Fault = null;
|
||||
Array.Clear(_occupied);
|
||||
OnStatusChanged?.Invoke();
|
||||
}
|
||||
|
||||
/// <summary>Báo lỗi cấu hình 1 lần (không spam mỗi chu kỳ poll).</summary>
|
||||
private void Warn(string message)
|
||||
{
|
||||
if (_lastWarning == message) return;
|
||||
_lastWarning = message;
|
||||
logger.LogWarning("ASRS OPC UA: {Message}", message);
|
||||
notif?.Notify("ASRS", "OPC UA", "error", message);
|
||||
}
|
||||
|
||||
private static bool? ToBool(object? v) => v is bool b ? b : null;
|
||||
|
||||
private static bool Upd(Func<bool?> getter, Action<bool?> setter, bool? newVal)
|
||||
{
|
||||
if (getter() == newVal) return false;
|
||||
setter(newVal);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
95
Lab505/Infrastructure/Protocols/OpcUa/AsrsNodeIds.cs
Normal file
95
Lab505/Infrastructure/Protocols/OpcUa/AsrsNodeIds.cs
Normal file
@@ -0,0 +1,95 @@
|
||||
using Lab505.Shared;
|
||||
using Opc.Ua;
|
||||
|
||||
namespace Lab505.Infrastructure.Protocols.OpcUa;
|
||||
|
||||
/// <summary>NodeId thật của gateway ASRS, tìm theo BrowseName lúc kết nối (xem AsrsNodeIds.ResolveAsync).</summary>
|
||||
public sealed class AsrsNodeMap
|
||||
{
|
||||
public required NodeId Homed { get; init; }
|
||||
public required NodeId Ready { get; init; }
|
||||
public required NodeId Busy { get; init; }
|
||||
public required NodeId Fault { get; init; }
|
||||
|
||||
/// <summary>Slot.{col}.{shelf}/Occupied, index = AsrsOpcLayout.SlotIndex(col, shelf).</summary>
|
||||
public required NodeId[] Occupied { get; init; }
|
||||
|
||||
public required NodeId Home { get; init; }
|
||||
public required NodeId Retrieve { get; init; }
|
||||
public required NodeId Store { get; init; }
|
||||
public required NodeId StoreAny { get; init; }
|
||||
public required NodeId Move { 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];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Giao diện của gateway AsrsOpcUaServer (ASRS_OPC_UA_Fix.md / Nodeset.xml), namespace "http://phenikaa.com/UA/ASRS/".
|
||||
/// Giống IMR/Dobot (UaNodeResolver), Lab505 tìm node THEO TÊN chứ không gán cứng NodeId:
|
||||
/// dùng TranslateBrowsePathsToNodeIds từ Objects theo BrowseName — chạy được dù server đặt NodeId
|
||||
/// dạng "ns;s=Ready", "ns;s=Objects.Ready" hay số.
|
||||
///
|
||||
/// Objects/Homed, Ready, Busy, Fault — Boolean
|
||||
/// Objects/Slot.{col}.{shelf}/Occupied — Boolean (col 1..3, shelf 1..4)
|
||||
/// Objects/Home() → [StatusCode:Int32]
|
||||
/// Objects/Retrieve(col, shelf, conveyor:UInt16) → [StatusCode] — lấy khay ra băng tải
|
||||
/// Objects/Store(col, shelf, conveyor:UInt16) → [StatusCode] — trả khay từ băng tải vào ô
|
||||
/// Objects/StoreAny(conveyor:UInt16) → [StatusCode, col, shelf]
|
||||
/// Objects/Move(fromCol, fromShelf, toCol, toShelf) → [StatusCode]
|
||||
/// Method gọi trên ObjectsFolder (i=85).
|
||||
/// </summary>
|
||||
public static class AsrsNodeIds
|
||||
{
|
||||
public const string NamespaceUri = "http://phenikaa.com/UA/ASRS/";
|
||||
|
||||
public static NodeId MethodOwner => ObjectIds.ObjectsFolder;
|
||||
|
||||
private static readonly string[] RootNames =
|
||||
["Homed", "Ready", "Busy", "Fault", "Home", "Retrieve", "Store", "StoreAny", "Move"];
|
||||
|
||||
/// <summary>
|
||||
/// Tìm toàn bộ node theo BrowseName. Trả Map = null kèm danh sách đường dẫn không tìm thấy nếu thiếu node.
|
||||
/// </summary>
|
||||
public static async Task<(AsrsNodeMap? Map, string[] Missing)> ResolveAsync(
|
||||
OpcUaClient ua, ushort ns, CancellationToken ct = default)
|
||||
{
|
||||
var labels = new List<string>();
|
||||
var paths = new List<QualifiedName[]>();
|
||||
|
||||
foreach (var name in RootNames)
|
||||
{
|
||||
labels.Add(name);
|
||||
paths.Add([new QualifiedName(name, ns)]);
|
||||
}
|
||||
for (int i = 0; i < AsrsOpcLayout.SlotCount; i++)
|
||||
{
|
||||
int col = i % AsrsOpcLayout.Columns + 1, shelf = i / AsrsOpcLayout.Columns + 1;
|
||||
var slot = $"Slot.{col}.{shelf}";
|
||||
labels.Add($"{slot}/Occupied");
|
||||
paths.Add([new QualifiedName(slot, ns), new QualifiedName("Occupied", ns)]);
|
||||
}
|
||||
|
||||
var ids = await ua.TranslateBrowsePathsAsync(ObjectIds.ObjectsFolder, paths, ct);
|
||||
|
||||
var missing = labels.Where((_, i) => ids[i] is null).ToArray();
|
||||
if (missing.Length > 0)
|
||||
return (null, missing);
|
||||
|
||||
NodeId Id(string name) => ids[Array.IndexOf(RootNames, name)]!;
|
||||
var map = new AsrsNodeMap
|
||||
{
|
||||
Homed = Id("Homed"),
|
||||
Ready = Id("Ready"),
|
||||
Busy = Id("Busy"),
|
||||
Fault = Id("Fault"),
|
||||
Home = Id("Home"),
|
||||
Retrieve = Id("Retrieve"),
|
||||
Store = Id("Store"),
|
||||
StoreAny = Id("StoreAny"),
|
||||
Move = Id("Move"),
|
||||
Occupied = ids.Skip(RootNames.Length).Select(id => id!).ToArray()
|
||||
};
|
||||
return (map, []);
|
||||
}
|
||||
}
|
||||
@@ -35,6 +35,15 @@ public class OpcUaClient(string EndpointUrl, string configSection, ILogger logge
|
||||
public event Action<bool>? ConnectChanged;
|
||||
public int KeepAliveInterval { get; init; } = 1000;
|
||||
|
||||
/// <summary>Tên thiết bị hiển thị trong thông báo kết nối.</summary>
|
||||
public string Name { get; init; } = "Dobot";
|
||||
|
||||
/// <summary>
|
||||
/// true: khi kết nối sẽ browse server và cập nhật RCSNodeIds + Generated/RCSNodeIds.g.cs (server RCS của IMR/Dobot).
|
||||
/// Đặt false cho server khác (vd ASRS gateway) để không ghi đè map của RCS.
|
||||
/// </summary>
|
||||
public bool PublishRcsNodeIds { get; init; } = true;
|
||||
|
||||
public bool IsConnected => session != null && session.Connected;
|
||||
|
||||
// ====================================================================================
|
||||
@@ -85,7 +94,7 @@ public class OpcUaClient(string EndpointUrl, string configSection, ILogger logge
|
||||
|
||||
logger.LogWarning("OPC UA disconnected (endpoint switch → {Url})", _endpointUrl);
|
||||
ConnectChanged?.Invoke(false);
|
||||
notif?.Notify("[OPC] Dobot ngắt kết nối (switch endpoint)", "warning");
|
||||
notif?.Notify($"[OPC] {Name} ngắt kết nối (switch endpoint)", "warning");
|
||||
}
|
||||
|
||||
private async Task ConnectLoop(CancellationToken token)
|
||||
@@ -143,16 +152,19 @@ public class OpcUaClient(string EndpointUrl, string configSection, ILogger logge
|
||||
|
||||
session.KeepAlive += Session_KeepAlive;
|
||||
|
||||
_resolver = new UaNodeResolver(session);
|
||||
if (PublishRcsNodeIds)
|
||||
{
|
||||
_resolver = new UaNodeResolver(session);
|
||||
|
||||
GenerateRcsNodeIds(_resolver);
|
||||
GenerateRcsNodeIds(_resolver);
|
||||
|
||||
foreach (var kv in _resolver.Map)
|
||||
RCSNodeIds.Update(kv.Key, kv.Value);
|
||||
foreach (var kv in _resolver.Map)
|
||||
RCSNodeIds.Update(kv.Key, kv.Value);
|
||||
}
|
||||
|
||||
logger.LogInformation("OPC UA connected: {Url}", _endpointUrl);
|
||||
ConnectChanged?.Invoke(true);
|
||||
notif?.Notify("[OPC] Dobot kết nối thành công", "success");
|
||||
notif?.Notify($"[OPC] {Name} kết nối thành công", "success");
|
||||
}
|
||||
|
||||
// ====================================================================================
|
||||
@@ -173,7 +185,7 @@ public class OpcUaClient(string EndpointUrl, string configSection, ILogger logge
|
||||
sessionReconnectHandler.BeginReconnect(session, null, 1000, Client_ReconnectComplete);
|
||||
logger.LogWarning("OPC UA connection lost (KeepAlive bad status: {Status})", e.Status);
|
||||
ConnectChanged?.Invoke(false);
|
||||
notif?.Notify("[OPC] Dobot mất kết nối !", "error");
|
||||
notif?.Notify($"[OPC] {Name} mất kết nối !", "error");
|
||||
}
|
||||
}
|
||||
catch (Exception ex)
|
||||
@@ -283,6 +295,63 @@ public class OpcUaClient(string EndpointUrl, string configSection, ILogger logge
|
||||
public IList<object> Call(NodeId objectId, NodeId methodId, params object[] args)
|
||||
=> CallAsync(objectId, methodId, args).GetAwaiter().GetResult();
|
||||
|
||||
/// <summary>
|
||||
/// Giống CallAsync nhưng không nuốt lỗi: ném InvalidOperationException khi chưa kết nối,
|
||||
/// ServiceResultException khi server từ chối — caller biết chắc lệnh có tới server hay không.
|
||||
/// Không giữ _opcLock: method có thể chạy nhiều phút (ASRS chờ PLC xong), Read/poll vẫn phải chạy song song.
|
||||
/// </summary>
|
||||
public async Task<IList<object>> CallCheckedAsync(NodeId objectId, NodeId methodId, object[] args,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var s = session;
|
||||
if (s == null || !s.Connected)
|
||||
throw new InvalidOperationException($"OPC UA {Name} chưa kết nối");
|
||||
|
||||
return await s.CallAsync(objectId, methodId, ct, args);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Tìm NodeId theo đường dẫn BrowseName (TranslateBrowsePathsToNodeIds) — không phụ thuộc NodeId server tự đặt.
|
||||
/// Mỗi bước đi theo HierarchicalReferences (gồm Organizes, HasComponent, ...).
|
||||
/// Phần tử kết quả = null nếu đường dẫn không tồn tại.
|
||||
/// </summary>
|
||||
public async Task<NodeId?[]> TranslateBrowsePathsAsync(NodeId startNode, IReadOnlyList<QualifiedName[]> paths,
|
||||
CancellationToken ct = default)
|
||||
{
|
||||
var s = session;
|
||||
if (s == null || !s.Connected)
|
||||
throw new InvalidOperationException($"OPC UA {Name} chưa kết nối");
|
||||
|
||||
var browsePaths = new BrowsePathCollection(paths.Select(path => new BrowsePath
|
||||
{
|
||||
StartingNode = startNode,
|
||||
RelativePath = new RelativePath
|
||||
{
|
||||
Elements = new RelativePathElementCollection(path.Select(name => new RelativePathElement
|
||||
{
|
||||
ReferenceTypeId = ReferenceTypeIds.HierarchicalReferences,
|
||||
IncludeSubtypes = true,
|
||||
IsInverse = false,
|
||||
TargetName = name
|
||||
}))
|
||||
}
|
||||
}));
|
||||
|
||||
var response = await s.TranslateBrowsePathsToNodeIdsAsync(null, browsePaths, ct);
|
||||
return response.Results
|
||||
.Select(r => StatusCode.IsGood(r.StatusCode) && r.Targets.Count > 0
|
||||
? ExpandedNodeId.ToNodeId(r.Targets[0].TargetId, s.NamespaceUris)
|
||||
: null)
|
||||
.ToArray();
|
||||
}
|
||||
|
||||
/// <summary>Namespace index của <paramref name="uri"/> trên server hiện tại, -1 nếu chưa kết nối hoặc không có.</summary>
|
||||
public int GetNamespaceIndex(string uri)
|
||||
{
|
||||
var s = session;
|
||||
return s != null && s.Connected ? s.NamespaceUris.GetIndex(uri) : -1;
|
||||
}
|
||||
|
||||
// ====================================================================================
|
||||
// AUTO GENERATE RCSNodeIds.g.cs
|
||||
// ====================================================================================
|
||||
|
||||
@@ -52,6 +52,21 @@ internal static class StateDtoFactory
|
||||
driver.IsBusy, locked, driver.LastError);
|
||||
}
|
||||
|
||||
/// <summary>driver = null (sim stack) → Available=false.</summary>
|
||||
public static AsrsOpcPushDto BuildAsrsOpcDto(AsrsOpcDriver? driver)
|
||||
{
|
||||
if (driver is null)
|
||||
return new AsrsOpcPushDto(false, false, null, null, null, null,
|
||||
new bool?[AsrsOpcLayout.SlotCount], false, null, null);
|
||||
|
||||
var s = driver.State;
|
||||
return new AsrsOpcPushDto(
|
||||
true, s.IsOnline,
|
||||
s.Homed, s.Ready, s.Busy, s.Fault,
|
||||
s.OccupiedSnapshot(),
|
||||
driver.IsBusy, driver.CurrentOp, driver.LastError);
|
||||
}
|
||||
|
||||
public static WorkflowStateDto BuildWorkflowDto(
|
||||
FlowService wf, RobotCommandTracker tracker,
|
||||
DeviceCommandQueue imrQueue, DeviceCommandQueue amrQueue, DeviceCommandQueue dobotQueue)
|
||||
|
||||
@@ -33,6 +33,7 @@ public class StatePushService : IHostedService
|
||||
private readonly OpcUaClient _ua;
|
||||
private readonly INotificationService _notif;
|
||||
private readonly DeviceGroupLock _realLocks;
|
||||
private readonly AsrsOpcDriver _asrsOpc;
|
||||
|
||||
private readonly ILogger<StatePushService> _logger;
|
||||
|
||||
@@ -61,6 +62,7 @@ public class StatePushService : IHostedService
|
||||
OpcUaClient ua,
|
||||
INotificationService notif,
|
||||
DeviceGroupLock realLocks,
|
||||
AsrsOpcDriver asrsOpc,
|
||||
ILogger<StatePushService> logger,
|
||||
[FromKeyedServices("imr")] DeviceCommandQueue imrQueue,
|
||||
[FromKeyedServices("amr")] DeviceCommandQueue amrQueue,
|
||||
@@ -82,6 +84,7 @@ public class StatePushService : IHostedService
|
||||
_ua = ua;
|
||||
_notif = notif;
|
||||
_realLocks = realLocks;
|
||||
_asrsOpc = asrsOpc;
|
||||
_logger = logger;
|
||||
}
|
||||
|
||||
@@ -100,6 +103,8 @@ public class StatePushService : IHostedService
|
||||
_modeService.OnModeChanged += OnModeChanged;
|
||||
_ua.ConnectChanged += OnOpcUaConnectChanged;
|
||||
_realLocks.OnChanged += PushLockState;
|
||||
_asrsOpc.State.OnStatusChanged += PushAsrsOpcState;
|
||||
_asrsOpc.OnOperationStateChanged += PushAsrsOpcState;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
@@ -118,6 +123,8 @@ public class StatePushService : IHostedService
|
||||
_modeService.OnModeChanged -= OnModeChanged;
|
||||
_ua.ConnectChanged -= OnOpcUaConnectChanged;
|
||||
_realLocks.OnChanged -= PushLockState;
|
||||
_asrsOpc.State.OnStatusChanged -= PushAsrsOpcState;
|
||||
_asrsOpc.OnOperationStateChanged -= PushAsrsOpcState;
|
||||
return Task.CompletedTask;
|
||||
}
|
||||
|
||||
@@ -143,6 +150,7 @@ public class StatePushService : IHostedService
|
||||
await caller.SendAsync(HubContracts.AmrStateEvent, BuildRobotDto(_amr));
|
||||
await caller.SendAsync(HubContracts.ConveyorStateEvent, BuildConveyorDto());
|
||||
await caller.SendAsync(HubContracts.AsrsStateEvent, BuildAsrsDto());
|
||||
await caller.SendAsync(HubContracts.AsrsOpcStateEvent, StateDtoFactory.BuildAsrsOpcDto(_asrsOpc));
|
||||
await caller.SendAsync(HubContracts.WorkflowStateEvent, BuildWorkflowDto());
|
||||
await caller.SendAsync(HubContracts.SystemStateEvent, BuildSystemDto());
|
||||
await caller.SendAsync(HubContracts.LockStateEvent, BuildLockDto());
|
||||
@@ -184,6 +192,7 @@ public class StatePushService : IHostedService
|
||||
Fire(PushConveyorStateAsync);
|
||||
}
|
||||
private void PushAsrsState() => Fire(PushAsrsStateAsync);
|
||||
private void PushAsrsOpcState() => Fire(PushAsrsOpcStateAsync);
|
||||
private void PushWorkflowState() => Fire(PushWorkflowStateAsync);
|
||||
private void PushSystemState() => Fire(PushSystemStateAsync);
|
||||
private void PushLockState() => Fire(PushLockStateAsync);
|
||||
@@ -206,6 +215,9 @@ public class StatePushService : IHostedService
|
||||
private Task PushAsrsStateAsync()
|
||||
=> _hub.Clients.Group(Hubs.StateHub.RealGroup).SendAsync(HubContracts.AsrsStateEvent, BuildAsrsDto());
|
||||
|
||||
private Task PushAsrsOpcStateAsync()
|
||||
=> _hub.Clients.Group(Hubs.StateHub.RealGroup).SendAsync(HubContracts.AsrsOpcStateEvent, StateDtoFactory.BuildAsrsOpcDto(_asrsOpc));
|
||||
|
||||
private Task PushWorkflowStateAsync()
|
||||
=> _hub.Clients.Group(Hubs.StateHub.RealGroup).SendAsync(HubContracts.WorkflowStateEvent, BuildWorkflowDto());
|
||||
|
||||
|
||||
@@ -54,6 +54,13 @@ public record ConveyorCommandRequest(string Action);
|
||||
/// <summary>POST body for ASRS pick/return. Column: X1|X2|X3, Shelves: 12|43</summary>
|
||||
public record AsrsSlotRequest(string Column, string Shelves);
|
||||
|
||||
// ── ASRS qua OPC UA (gateway AsrsOpcUaServer) ────────────────────────────────
|
||||
|
||||
/// <summary>Retrieve/Store: Column 1..3, Shelf 1..4, Conveyor 1 = băng tải trái, 2 = phải.</summary>
|
||||
public record AsrsOpcSlotRequest(int Column, int Shelf, int Conveyor);
|
||||
public record AsrsOpcConveyorRequest(int Conveyor);
|
||||
public record AsrsOpcMoveRequest(int FromColumn, int FromShelf, int ToColumn, int ToShelf);
|
||||
|
||||
/// <summary>Một action đang chạy trên robot (từ VDA5050 ActionState).</summary>
|
||||
public record ShareRobotAction(string Type, string Status);
|
||||
|
||||
|
||||
@@ -8,6 +8,7 @@ using Lab505.Infrastructure.Drivers.Conveyor;
|
||||
using Lab505.Infrastructure.Drivers;
|
||||
using Lab505.Infrastructure.Drivers.Imr;
|
||||
using Lab505.Infrastructure.Drivers.Amr;
|
||||
using Lab505.Infrastructure.Push;
|
||||
using System.Security.Claims;
|
||||
|
||||
namespace Lab505.Presentation.Api;
|
||||
@@ -580,5 +581,57 @@ public static class RobotApiExtensions
|
||||
var id = tracker.Start(work);
|
||||
return Results.Accepted($"/api/operations/{id}", new OperationAccepted(id));
|
||||
});
|
||||
|
||||
// ── ASRS qua OPC UA (gateway AsrsOpcUaServer) — chỉ real stack ─────────
|
||||
var opc = asrs.MapGroup("/opc");
|
||||
|
||||
opc.MapGet("/status", (UserContextResolver res, HttpContext ctx)
|
||||
=> Results.Ok(StateDtoFactory.BuildAsrsOpcDto(res.Resolve(ctx).AsrsOpc)));
|
||||
|
||||
opc.MapPost("/home", (UserContextResolver res, HttpContext ctx, OperationTracker tracker)
|
||||
=> StartAsrsOpc(res, ctx, tracker,
|
||||
d => d.RequireCanHome(),
|
||||
(d, ct) => d.Home(ct)));
|
||||
|
||||
opc.MapPost("/retrieve", (AsrsOpcSlotRequest req, UserContextResolver res, HttpContext ctx, OperationTracker tracker)
|
||||
=> StartAsrsOpc(res, ctx, tracker,
|
||||
d => d.RequireCanRetrieve(req.Column, req.Shelf, req.Conveyor),
|
||||
(d, ct) => d.Retrieve(req.Column, req.Shelf, req.Conveyor, ct)));
|
||||
|
||||
opc.MapPost("/store", (AsrsOpcSlotRequest req, UserContextResolver res, HttpContext ctx, OperationTracker tracker)
|
||||
=> StartAsrsOpc(res, ctx, tracker,
|
||||
d => d.RequireCanStore(req.Column, req.Shelf, req.Conveyor),
|
||||
(d, ct) => d.Store(req.Column, req.Shelf, req.Conveyor, ct)));
|
||||
|
||||
opc.MapPost("/store-any", (AsrsOpcConveyorRequest req, UserContextResolver res, HttpContext ctx, OperationTracker tracker)
|
||||
=> StartAsrsOpc(res, ctx, tracker,
|
||||
d => d.RequireCanStoreAny(req.Conveyor),
|
||||
(d, ct) => d.StoreAny(req.Conveyor, ct)));
|
||||
|
||||
opc.MapPost("/move", (AsrsOpcMoveRequest req, UserContextResolver res, HttpContext ctx, OperationTracker tracker)
|
||||
=> StartAsrsOpc(res, ctx, tracker,
|
||||
d => d.RequireCanMove(req.FromColumn, req.FromShelf, req.ToColumn, req.ToShelf),
|
||||
(d, ct) => d.Move(req.FromColumn, req.FromShelf, req.ToColumn, req.ToShelf, ct)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Lock C2·ASRS + workflow guard → kiểm tra điều kiện (trả 400/409/503 ngay) → chạy nền qua OperationTracker.
|
||||
/// </summary>
|
||||
private static IResult StartAsrsOpc(
|
||||
UserContextResolver res, HttpContext ctx, OperationTracker tracker,
|
||||
Action<AsrsOpcDriver> validate,
|
||||
Func<AsrsOpcDriver, CancellationToken, Task> work)
|
||||
{
|
||||
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 { validate(driver); }
|
||||
catch (ArgumentException ex) { return Results.BadRequest(new { error = ex.Message }); }
|
||||
catch (AsrsOpcUnavailableException ex) { return Results.Json(new { error = ex.Message }, statusCode: 503); }
|
||||
catch (InvalidOperationException ex) { return Results.Conflict(new { error = ex.Message }); }
|
||||
|
||||
var id = tracker.Start(ct => work(driver, ct));
|
||||
return Results.Accepted($"/api/operations/{id}", new OperationAccepted(id));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -164,6 +164,24 @@ builder.Services.AddSingleton<OpcUaClient>(sp =>
|
||||
});
|
||||
builder.Services.AddHostedService<OpcUaClientHostedService>();
|
||||
|
||||
// ------------ ASRS OPC UA CLIENT (gateway AsrsOpcUaServer → Modbus → PLC ASRS) ------------
|
||||
// Client riêng, không dùng chung OpcUaClient của IMR/Dobot. Chỉ có trên real stack.
|
||||
builder.Services.AddSingleton(_ => AsrsOpcOptions.From(config));
|
||||
builder.Services.AddSingleton<AsrsOpcState>(sp =>
|
||||
{
|
||||
var opt = sp.GetRequiredService<AsrsOpcOptions>();
|
||||
var notif = sp.GetRequiredService<INotificationService>();
|
||||
var ua = new OpcUaClient(opt.EndpointUrl, opt.ConfigSection, sp.GetRequiredService<ILogger<OpcUaClient>>(), notif)
|
||||
{
|
||||
Name = "ASRS",
|
||||
PublishRcsNodeIds = false,
|
||||
KeepAliveInterval = opt.KeepAliveIntervalMs
|
||||
};
|
||||
return new AsrsOpcState(ua, opt, sp.GetRequiredService<ILogger<AsrsOpcState>>(), notif);
|
||||
});
|
||||
builder.Services.AddHostedService(sp => sp.GetRequiredService<AsrsOpcState>());
|
||||
builder.Services.AddSingleton<AsrsOpcDriver>();
|
||||
|
||||
// ------------ VDA API ------------
|
||||
builder.Services.AddSingleton<IApiService, ApiService>();
|
||||
|
||||
|
||||
@@ -62,6 +62,15 @@
|
||||
"KeepAliveIntervalMs": 5000,
|
||||
"Description": "Dobot Robot Arm OPC UA Server",
|
||||
"AutoConnect": true
|
||||
},
|
||||
{
|
||||
"Name": "ASRS",
|
||||
"EndpointUrl": "opc.tcp://192.168.111.50: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",
|
||||
"PollIntervalMs": 300,
|
||||
"StateSyncTimeoutMs": 5000
|
||||
}
|
||||
]
|
||||
},
|
||||
|
||||
Reference in New Issue
Block a user