initial commit

This commit is contained in:
robotics_x1
2026-10-12 15:24:08 +07:00
commit 55228b3772
367 changed files with 162893 additions and 0 deletions

View File

@@ -0,0 +1,211 @@
@implements IAsyncDisposable
<MudPaper Elevation="0" Class="pa-3" Style="background:transparent;">
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center"
Style="cursor:pointer" @onclick="ToggleAMR">
<MudText Typo="Typo.subtitle1">AMR</MudText>
<MudIcon Icon="@(IsAmrExpanded ? 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="@AmrMudColor" />
<div>
<MudText Typo="Typo.caption">@AmrStatus.ToUpper()</MudText>
<MudText Typo="Typo.caption" Style="color:#9a9a9a;">
Errors: @(State.Amr.Errors is { Count: > 0 } errs ? string.Join(", ", errs) : "none")
</MudText>
</div>
</div>
<div class="mt-1 mb-1">
<MudButton FullWidth="true" Variant="Variant.Outlined" Color="Color.Error" Size="Size.Small" OnClick="Cancel_Vda" Disabled="@(!State.CanControl)">Cancel</MudButton>
</div>
@if (IsAmrExpanded)
{
<MudText Typo="Typo.caption" Class="sec-title mt-2">Move</MudText>
<div class="op-grid">
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="MovetoCap1" Disabled="@AmrLocked("MoveTo Cap1")">Cap1</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="MovetoCap2" Disabled="@AmrLocked("MoveTo Cap2")">Cap2</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="MovetoHome" Disabled="@AmrLocked("MoveTo Home")">Home</MudButton>
</div>
<MudText Typo="Typo.caption" Class="sec-title mt-2">Action</MudText>
<div class="op-grid">
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="AMR_Load" Disabled="@AmrLocked("Load")">Load</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="AMR_Unload" Disabled="@AmrLocked("Unload")">Unload</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="UndockFromStation" Disabled="@UndockBlocked()">Undock</MudButton>
</div>
<MudText Typo="Typo.caption" Class="sec-title mt-2">NAV</MudText>
<div class="op-grid-2">
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Resume" Disabled="@(!State.CanControl)">Resume</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Pause" Disabled="@(!State.CanControl)">Pause</MudButton>
</div>
<div class="op-grid-4 mt-2">
<MudNumericField T="double?" @bind-Value="_poseX" Placeholder="X" Variant="Variant.Outlined"
Format="F3" Step="0.01" Culture="@System.Globalization.CultureInfo.InvariantCulture"
HideSpinButtons="true" Class="pnl-num" />
<MudNumericField T="double?" @bind-Value="_poseY" Placeholder="Y" Variant="Variant.Outlined"
Format="F3" Step="0.01" Culture="@System.Globalization.CultureInfo.InvariantCulture"
HideSpinButtons="true" Class="pnl-num" />
<MudNumericField T="double?" @bind-Value="_poseTheta" Placeholder="θ" Variant="Variant.Outlined"
Format="F3" Step="0.01" Culture="@System.Globalization.CultureInfo.InvariantCulture"
HideSpinButtons="true" Class="pnl-num" />
<MudButton Variant="Variant.Outlined" Size="Size.Small" Color="Color.Warning"
StartIcon="@(_settingPose ? Icons.Material.Filled.HourglassBottom : null)"
OnClick="RunInitPosition" Disabled="@(_settingPose || !State.CanControl)">
@(_settingPose ? "..." : "InitPos")
</MudButton>
</div>
}
</MudPaper>
@code {
[Inject] StateService State { get; set; } = default!;
[Inject] CommandService Cmd { get; set; } = default!;
[Inject] ISnackbar Snackbar { get; set; } = default!;
[Inject] LangService Lang { get; set; } = default!;
bool IsAmrExpanded = true;
void ToggleAMR() => IsAmrExpanded = !IsAmrExpanded;
private double? _poseX;
private double? _poseY;
private double? _poseTheta;
private bool _settingPose;
private CancellationTokenSource? _initPoseCts;
protected override async Task OnInitializedAsync()
{
await State.StartAsync();
State.AmrChanged += Refresh;
State.WorkflowChanged += Refresh;
Lang.LangChanged += Refresh;
}
public ValueTask DisposeAsync()
{
State.AmrChanged -= Refresh;
State.WorkflowChanged -= Refresh;
Lang.LangChanged -= Refresh;
try { _initPoseCts?.Cancel(); } catch { }
_initPoseCts?.Dispose();
_initPoseCts = null;
return ValueTask.CompletedTask;
}
private void Refresh() => InvokeAsync(StateHasChanged);
private string AmrStatus
{
get
{
var s = State.Amr;
if (!s.IsOnline) return "off";
if (s.Errors.Count > 0) return "error";
if (s.NewBaseRequest == false) return "moving";
return "ok";
}
}
private Color AmrMudColor => AmrStatus switch
{
"ok" => Color.Success,
"moving" => Color.Info,
"error" => Color.Error,
_ => Color.Default
};
private Task Cancel_Vda() => Cmd.AmrCancelAsync();
// Nút bị khóa nếu là lệnh đang chạy HOẶC lệnh đang chờ trong hàng đợi, hoặc không có quyền điều khiển
private bool AmrLocked(string label)
=> !State.CanControl || State.Workflow.AmrBusyLabel == label || State.Workflow.AmrNextLabel == label;
// Undock bị khóa khi không ở trạm dock hoặc đang bận
private bool UndockBlocked() => AmrLocked("Undock") || !AmrAtDock();
// Cảnh báo khi robot online+idle tại Home (không phải trạm dock)
private bool AmrIdleAtHome()
{
var s = State.Amr;
return s.IsOnline && s.NewBaseRequest == true
&& Near(s.X, s.Y, RobotPositions.AMR_HOME_X, RobotPositions.AMR_HOME_Y);
}
private static bool Near(double x, double y, double tx, double ty)
=> Math.Abs(x - tx) < RobotPositions.POS_TOL && Math.Abs(y - ty) < RobotPositions.POS_TOL;
private bool AmrAtDock()
{
var s = State.Amr;
return Near(s.X, s.Y, RobotPositions.AMR_CAP1_X, RobotPositions.AMR_CAP1_Y)
|| Near(s.X, s.Y, RobotPositions.AMR_CAP2_X, RobotPositions.AMR_CAP2_Y);
}
private Task MovetoCap1()
{
if (AmrAtDock() && State.Workflow.AmrCmd != "undocking")
{ Snackbar.Add(Lang.T("AMR đang docked — lùi trước khi di chuyển!", "AMR is docked — undock before moving!"), Severity.Warning); return Task.CompletedTask; }
return Cmd.AmrMoveToAsync("Cap1");
}
private Task MovetoCap2()
{
if (AmrAtDock() && State.Workflow.AmrCmd != "undocking")
{ Snackbar.Add(Lang.T("AMR đang docked — lùi trước khi di chuyển!", "AMR is docked — undock before moving!"), Severity.Warning); return Task.CompletedTask; }
return Cmd.AmrMoveToAsync("Cap2");
}
private Task MovetoHome() => Cmd.AmrMoveToAsync("Home");
private Task AMR_Load() => Cmd.AmrLoadAsync();
private Task AMR_Unload() => Cmd.AmrUnloadAsync();
private Task UndockFromStation()=> Cmd.AmrUndockAsync();
private Task Pause() => Cmd.AmrPauseAsync();
private Task Resume() => Cmd.AmrResumeAsync();
private async Task RunInitPosition()
{
_initPoseCts?.Dispose();
_initPoseCts = new CancellationTokenSource();
var ct = _initPoseCts.Token;
_settingPose = true;
await InvokeAsync(StateHasChanged);
try
{
var x = _poseX ?? 0;
var y = _poseY ?? 0;
var theta = _poseTheta ?? 0;
// VDA initPosition instant action
await Cmd.AmrInitPositionAsync(x, y, theta, ct);
Snackbar.Add(
Lang.T(
$"Đã gửi InitPosition ({x:F2}, {y:F2}, {theta:F2})",
$"InitPosition sent ({x:F2}, {y:F2}, {theta:F2})"),
Severity.Success);
}
catch (OperationCanceledException)
{
Snackbar.Add(Lang.T("InitPosition đã huỷ", "InitPosition cancelled"), Severity.Info);
}
finally
{
_settingPose = false;
_initPoseCts?.Dispose();
_initPoseCts = null;
await InvokeAsync(StateHasChanged);
}
}
}
<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:1fr 1fr; gap:5px; }
.op-grid-4 { display:grid; grid-template-columns:repeat(4, 1fr); gap:5px; }
</style>

View File

@@ -0,0 +1,87 @@
@implements IAsyncDisposable
<MudPaper Elevation="0" Class="pa-2" Style="background:transparent;">
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center"
Style="cursor:pointer" @onclick="ToggleASRS">
<MudText Typo="Typo.subtitle1">ASRS</MudText>
<MudIcon Icon="@(IsAsrsExpanded ? Icons.Material.Filled.ExpandMore : Icons.Material.Filled.ExpandLess)" Size="Size.Small" />
</MudStack>
<MudCollapse Expanded="@IsAsrsExpanded">
<MudText Typo="Typo.caption" Class="sec-title mt-2">Pick Empty Box (S34)</MudText>
<div class="op-grid">
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X1_S34", CanRun_S34(1)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X1_S34")'>X1_S34</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X2_S34", CanRun_S34(2)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X2_S34")'>X2_S34</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X3_S34", CanRun_S34(3)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X3_S34")'>X3_S34</MudButton>
</div>
<MudText Typo="Typo.caption" Class="sec-title mt-2">Pick Empty Box (S12)</MudText>
<div class="op-grid">
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X1_S12", CanRun_S12(1)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X1_S12")'>X1_S12</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X2_S12", CanRun_S12(2)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X2_S12")'>X2_S12</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X3_S12", CanRun_S12(3)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X3_S12")'>X3_S12</MudButton>
</div>
<MudText Typo="Typo.caption" Class="sec-title mt-2">Return Tray (R43)</MudText>
<div class="op-grid">
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X1_R43", CanRun_R43(1)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X1_R43")'>X1_R43</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X2_R43", CanRun_R43(2)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X2_R43")'>X2_R43</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X3_R43", CanRun_R43(3)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X3_R43")'>X3_R43</MudButton>
</div>
<MudText Typo="Typo.caption" Class="sec-title mt-2">Return Tray (R12)</MudText>
<div class="op-grid">
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X1_R12", CanRun_R12(1)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X1_R12")'>X1_R12</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X2_R12", CanRun_R12(2)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X2_R12")'>X2_R12</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" Disabled="@(!CanOp("X3_R12", CanRun_R12(3)))" OnClick='()=>Cmd.AsrsWorkflowAsync("X3_R12")'>X3_R12</MudButton>
</div>
<div class="mt-2">
<MudButton FullWidth="true" Variant="Variant.Outlined" Color="Color.Primary" Size="Size.Small"
Disabled="@(State.Asrs.IsBusy || !State.CanControl)" OnClick="Homing">Homing</MudButton>
</div>
</MudCollapse>
</MudPaper>
@code {
[Inject] StateService State { get; set; } = default!;
[Inject] CommandService Cmd { get; set; } = default!;
bool IsAsrsExpanded = true;
void ToggleASRS() => IsAsrsExpanded = !IsAsrsExpanded;
protected override async Task OnInitializedAsync()
{
await State.StartAsync();
State.AsrsChanged += Refresh;
}
public ValueTask DisposeAsync()
{
State.AsrsChanged -= Refresh;
return ValueTask.CompletedTask;
}
private void Refresh() => InvokeAsync(StateHasChanged);
private Task Homing() => Cmd.AsrsHomingAsync();
private bool CanOp(string label, bool canRun)
=> State.CanControl && !State.Asrs.IsBusy && !State.AsrsIsLocked(label)
&& State.Asrs.SAFETY_MODE == true && canRun;
private bool CanRun_S12(int col) => col switch { 1 => State.Asrs.X11 == true, 2 => State.Asrs.X12 == true, 3 => State.Asrs.X13 == true, _ => false };
private bool CanRun_R12(int col) => col switch { 1 => State.Asrs.X11 == false, 2 => State.Asrs.X12 == false, 3 => State.Asrs.X13 == false, _ => false };
private bool CanRun_S34(int col) => col switch { 1 => State.Asrs.X31 == true, 2 => State.Asrs.X32 == true, 3 => State.Asrs.X33 == true, _ => false };
private bool CanRun_R43(int col) => col switch { 1 => State.Asrs.X31 == false, 2 => State.Asrs.X32 == false, 3 => State.Asrs.X33 == false, _ => false };
}
<style>
.sec-title { display:block; color:#9CA3AF; margin-bottom:4px; }
.op-grid { display: grid; grid-template-columns: repeat(3, 1fr); gap: 5px; }
</style>

View File

@@ -0,0 +1,208 @@
@implements IAsyncDisposable
@inject HttpClient Http
<MudPaper Elevation="0" Class="pa-2" Style="background:transparent;">
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center"
Style="cursor:pointer" @onclick="ToggleExpand">
<MudText Typo="Typo.subtitle1">CONTROL</MudText>
<MudIcon Icon="@(_expanded ? Icons.Material.Filled.ExpandMore : Icons.Material.Filled.ExpandLess)" Size="Size.Small" />
</MudStack>
@if (IsLockBlocked)
{
<div style="background:rgba(255,100,0,0.08);border:1px solid rgba(255,100,0,0.25);border-radius:5px;padding:4px 8px;margin-bottom:4px;">
<MudText Typo="Typo.caption" Style="color:#f90;">@Lang.T("Bạn chưa giữ quyền điều khiển. Vào CONTROL ACCESS → TAKE CONTROL.", "You don't hold control. Go to CONTROL ACCESS → TAKE CONTROL.")</MudText>
</div>
}
<div class="always-row">
<MudButton Variant="Variant.Outlined" Color="Color.Error" Size="Size.Small" FullWidth="true"
OnClick="Cancel" Disabled="@(!IsAnyRunning)">
Cancel
</MudButton>
</div>
@if (_expanded)
{
<MudText Typo="Typo.caption" Class="sec-title mt-2">Params</MudText>
<div class="op-grid-2">
<MudNumericField T="int?" @bind-Value="_times" Placeholder="OK" Variant="Variant.Outlined" Class="pnl-num" Min="1" Max="99" />
<MudNumericField T="int?" @bind-Value="_ng" Placeholder="NG" Variant="Variant.Outlined" Class="pnl-num" Min="0" Max="99" />
</div>
<MudText Typo="Typo.caption" Class="sec-title mt-2">Test</MudText>
<div class="op-grid">
<MudButton Variant="Variant.Outlined" Color="Color.Tertiary" Size="Size.Small"
Disabled="@(IsAnyRunning || IsLockBlocked)"
OnClick='()=>RunOp("Test", ct => Cmd.WorkflowRunCycleAsync(_times ?? 1, _ng ?? 0, ct))'>No ASRS</MudButton>
</div>
<MudText Typo="Typo.caption" Class="sec-title mt-2">X_A</MudText>
<div class="op-grid">
<MudButton Variant="Variant.Outlined" Color="Color.Warning" Size="Size.Small" Disabled="@(!CanA(1))"
OnClick='()=>RunOp("X1A", ct => Cmd.WorkflowX1AAsync(_times ?? 1, _ng ?? 0, ct), GoodsGoneS34(1))'>X1A</MudButton>
<MudButton Variant="Variant.Outlined" Color="Color.Warning" Size="Size.Small" Disabled="@(!CanA(2))"
OnClick='()=>RunOp("X2A", ct => Cmd.WorkflowX2AAsync(_times ?? 1, _ng ?? 0, ct), GoodsGoneS34(2))'>X2A</MudButton>
<MudButton Variant="Variant.Outlined" Color="Color.Warning" Size="Size.Small" Disabled="@(!CanA(3))"
OnClick='()=>RunOp("X3A", ct => Cmd.WorkflowX3AAsync(_times ?? 1, _ng ?? 0, ct), GoodsGoneS34(3))'>X3A</MudButton>
</div>
<MudText Typo="Typo.caption" Class="sec-title mt-2">X_B</MudText>
<div class="op-grid">
<MudButton Variant="Variant.Outlined" Color="Color.Info" Size="Size.Small" Disabled="@(!CanB(1))"
OnClick='()=>RunOp("X1B", ct => Cmd.WorkflowX1BAsync(_times ?? 1, _ng ?? 0, ct), GoodsGoneS12(1))'>X1B</MudButton>
<MudButton Variant="Variant.Outlined" Color="Color.Info" Size="Size.Small" Disabled="@(!CanB(2))"
OnClick='()=>RunOp("X2B", ct => Cmd.WorkflowX2BAsync(_times ?? 1, _ng ?? 0, ct), GoodsGoneS12(2))'>X2B</MudButton>
<MudButton Variant="Variant.Outlined" Color="Color.Info" Size="Size.Small" Disabled="@(!CanB(3))"
OnClick='()=>RunOp("X3B", ct => Cmd.WorkflowX3BAsync(_times ?? 1, _ng ?? 0, ct), GoodsGoneS12(3))'>X3B</MudButton>
</div>
}
</MudPaper>
@code {
[Inject] StateService State { get; set; } = default!;
[Inject] CommandService Cmd { get; set; } = default!;
[Inject] LangService Lang { get; set; } = default!;
private bool _expanded = true;
void ToggleExpand() => _expanded = !_expanded;
private int? _times;
private int? _ng;
private string _myUserId = "";
private bool IsLockBlocked =>
!State.System.IsSimulation
&& State.LockState is not null
&& (State.LockState.Workflow is null || State.LockState.Workflow.UserId != _myUserId);
private readonly HashSet<string> _runningOps = new();
private readonly Dictionary<string, CancellationTokenSource> _opCts = new();
private Func<bool>? _goodsTaken;
private bool IsAnyRunning => _runningOps.Count > 0 || State.Workflow.IsRunning;
private bool CanA(int col) => !IsAnyRunning && State.CanControl && !IsLockBlocked && col switch
{
1 => State.Asrs.X31 == true || State.Asrs.X41 == true,
2 => State.Asrs.X32 == true || State.Asrs.X42 == true,
3 => State.Asrs.X33 == true || State.Asrs.X43 == true,
_ => false
};
private bool CanB(int col) => !IsAnyRunning && State.CanControl && !IsLockBlocked && col switch
{
1 => State.Asrs.X11 == true || State.Asrs.X21 == true,
2 => State.Asrs.X12 == true || State.Asrs.X22 == true,
3 => State.Asrs.X13 == true || State.Asrs.X23 == true,
_ => false
};
// "Goods taken" lambdas for SAFETY_MODE check — read from cached SignalR state
private Func<bool> GoodsGoneS34(int col) => col switch
{
1 => () => State.Asrs.X31 != true && State.Asrs.X41 != true,
2 => () => State.Asrs.X32 != true && State.Asrs.X42 != true,
_ => () => State.Asrs.X33 != true && State.Asrs.X43 != true,
};
private Func<bool> GoodsGoneS12(int col) => col switch
{
1 => () => State.Asrs.X11 != true && State.Asrs.X21 != true,
2 => () => State.Asrs.X12 != true && State.Asrs.X22 != true,
_ => () => State.Asrs.X13 != true && State.Asrs.X23 != true,
};
protected override async Task OnInitializedAsync()
{
await State.StartAsync();
State.WorkflowChanged += OnWorkflowChanged;
State.AsrsChanged += OnAsrsChanged;
State.LockStateChanged += OnLockChanged;
Lang.LangChanged += OnLockChanged;
try
{
var me = await Http.GetFromJsonAsync<MeCtrlDto>("/api/auth/me");
_myUserId = me?.UserId ?? "";
}
catch { }
}
public ValueTask DisposeAsync()
{
State.WorkflowChanged -= OnWorkflowChanged;
State.AsrsChanged -= OnAsrsChanged;
State.LockStateChanged -= OnLockChanged;
Lang.LangChanged -= OnLockChanged;
CancelAll();
return ValueTask.CompletedTask;
}
private void OnWorkflowChanged() => InvokeAsync(StateHasChanged);
private void OnLockChanged() => InvokeAsync(StateHasChanged);
private void OnAsrsChanged()
{
// SAFETY_MODE went off during an active operation → cancel unless goods already taken
if (State.Asrs.SAFETY_MODE == false && IsAnyRunning)
{
bool goodsDone = _goodsTaken != null && _goodsTaken();
if (!goodsDone)
InvokeAsync(CancelAll);
}
InvokeAsync(StateHasChanged);
}
private void Cancel() => CancelAll();
record MeCtrlDto(string? UserId);
private void CancelAll()
{
foreach (var cts in _opCts.Values) cts.Cancel();
_ = Cmd.WorkflowEmergencyStopAsync();
}
private void RunOp(string name, Func<CancellationToken, Task> action, Func<bool>? goodsTaken = null)
{
if (_runningOps.Contains(name)) return;
_goodsTaken = goodsTaken;
var cts = new CancellationTokenSource();
_opCts[name] = cts;
_ = ExecOpAsync(name, action, cts.Token);
}
private async Task ExecOpAsync(string name, Func<CancellationToken, Task> action, CancellationToken token)
{
await InvokeAsync(() => { _runningOps.Add(name); StateHasChanged(); });
try
{
await action(token);
await InvokeAsync(StateHasChanged);
}
catch (OperationCanceledException) { }
catch (Exception)
{
_ = Cmd.WorkflowEmergencyStopAsync();
}
finally
{
await InvokeAsync(() =>
{
_goodsTaken = null;
_runningOps.Remove(name);
if (_opCts.TryGetValue(name, out var c)) { c.Dispose(); _opCts.Remove(name); }
StateHasChanged();
});
}
}
}
<style>
.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:1fr 1fr; gap:5px; }
</style>

View File

@@ -0,0 +1,78 @@
@implements IAsyncDisposable
<div>
@if (State.Conveyor.WriteError != null)
{
<MudAlert Severity="Severity.Error" Dense="true" Class="mt-1" Style="font-size:0.7rem;">
@State.Conveyor.WriteError
</MudAlert>
}
<MudText Typo="Typo.caption" Class="sec-title mt-2">Conveyor 1</MudText>
<div class="op-grid-3">
@CoilBtn("Ready", () => State.Conveyor.C1Ready, (v) => SetCoil("c1", "ready", v))
@CoilBtn("In", () => State.Conveyor.C1In, (v) => SetCoil("c1", "in", v))
@CoilBtn("Out", () => State.Conveyor.C1Out, (v) => SetCoil("c1", "out", v))
@CoilBtn("IMRin", () => State.Conveyor.C1IMRin, (v) => SetCoil("c1", "imr-in", v))
@CoilBtn("IMRout", () => State.Conveyor.C1IMRout, (v) => SetCoil("c1", "imr-out", v))
@CoilBtn("Goods", () => State.Conveyor.C1HasGoods, (v) => SetCoil("c1", "has-goods", v))
@CoilBtn("Empty", () => State.Conveyor.C1NotGoods, (v) => SetCoil("c1", "not-goods", v))
</div>
<MudText Typo="Typo.caption" Class="sec-title mt-2">Conveyor 2</MudText>
<div class="op-grid-3">
@CoilBtn("Ready", () => State.Conveyor.C2Ready, (v) => SetCoil("c2", "ready", v))
@CoilBtn("In", () => State.Conveyor.C2In, (v) => SetCoil("c2", "in", v))
@CoilBtn("Out", () => State.Conveyor.C2Out, (v) => SetCoil("c2", "out", v))
@CoilBtn("Goods", () => State.Conveyor.C2HasGoods, (v) => SetCoil("c2", "has-goods", v))
@CoilBtn("Empty", () => State.Conveyor.C2NotGoods, (v) => SetCoil("c2", "not-goods", v))
</div>
</div>
@code {
[Parameter] public bool? ReadOnly { get; set; }
[Inject] StateService State { get; set; } = default!;
[Inject] CommandService Cmd { get; set; } = default!;
protected override async Task OnInitializedAsync()
{
await State.StartAsync();
State.ConveyorChanged += Refresh;
State.WorkflowChanged += Refresh;
State.SystemChanged += Refresh;
State.LockStateChanged += Refresh;
}
public ValueTask DisposeAsync()
{
State.ConveyorChanged -= Refresh;
State.WorkflowChanged -= Refresh;
State.SystemChanged -= Refresh;
State.LockStateChanged -= Refresh;
return ValueTask.CompletedTask;
}
private void Refresh() => InvokeAsync(StateHasChanged);
private bool IsDisabled => ReadOnly ?? (State.Workflow.IsRunning || !State.CanControl);
private Task SetCoil(string c, string coil, bool v) => Cmd.ConveyorSetCoilAsync(c, coil, v);
private RenderFragment CoilBtn(string label, Func<bool?> getter, Action<bool> setter) => __builder =>
{
bool on = getter() == true;
<MudButton Size="Size.Small"
Variant="@(on ? Variant.Filled : Variant.Outlined)"
Color="@(on ? Color.Success : Color.Default)"
Disabled="@IsDisabled"
OnClick="@(() => setter(!on))">
@label
</MudButton>
};
}
<style>
.sec-title { display:block; color:#9CA3AF; margin-bottom:4px; }
.op-grid-3 { display:grid; grid-template-columns:repeat(3, 1fr); gap:5px; }
</style>

View File

@@ -0,0 +1,96 @@
@implements IAsyncDisposable
<MudPaper Elevation="0" Class="pa-3" Style="background:transparent;">
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center"
Style="cursor:pointer" @onclick="ToggleExpand">
<MudText Typo="Typo.subtitle1">CONVEYOR</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.ToUpper()</MudText>
<MudText Typo="Typo.caption" Style="color:#9a9a9a;">@DetailText</MudText>
</div>
</div>
@if (_expanded)
{
<ConveyorPanel />
}
</MudPaper>
@code {
[Inject] StateService State { get; set; } = default!;
private bool _expanded = true;
protected override async Task OnInitializedAsync()
{
await State.StartAsync();
State.ConveyorChanged += Refresh;
State.WorkflowChanged += Refresh;
State.SystemChanged += Refresh;
State.LockStateChanged += Refresh;
}
public ValueTask DisposeAsync()
{
State.ConveyorChanged -= Refresh;
State.WorkflowChanged -= Refresh;
State.SystemChanged -= Refresh;
State.LockStateChanged -= Refresh;
return ValueTask.CompletedTask;
}
private void ToggleExpand() => _expanded = !_expanded;
private void Refresh() => InvokeAsync(StateHasChanged);
private bool C1Online => State.Conveyor.C1Out != null;
private bool C2Online => State.Conveyor.C2Out != null;
private bool AnyRunning =>
State.Conveyor.C1In == true ||
State.Conveyor.C1Out == true ||
State.Conveyor.C1IMRin == true ||
State.Conveyor.C1IMRout == true ||
State.Conveyor.C2In == true ||
State.Conveyor.C2Out == true;
private string StatusText
{
get
{
if (!string.IsNullOrWhiteSpace(State.Conveyor.WriteError)) return "error";
if (AnyRunning) return "running";
if (C1Online || C2Online) return "ok";
return "off";
}
}
private Color StatusColor => StatusText switch
{
"ok" => Color.Success,
"running" => Color.Info,
"error" => Color.Error,
_ => Color.Default
};
private string DetailText =>
$"C1: {LineState(C1Online, State.Conveyor.C1In, State.Conveyor.C1Out, State.Conveyor.C1IMRin, State.Conveyor.C1IMRout)} | " +
$"C2: {LineState(C2Online, State.Conveyor.C2In, State.Conveyor.C2Out)}";
private static string LineState(bool online, params bool?[] states)
{
if (!online) return "off";
return states.Any(v => v == true) ? "running" : "ready";
}
}
<style>
.status-row { display:flex; align-items:center; gap:8px; margin-bottom:4px; }
</style>

View File

@@ -0,0 +1,137 @@
@implements IAsyncDisposable
<MudPaper Elevation="0" Class="pa-3" Style="background:transparent;">
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center"
Style="cursor:pointer" @onclick="ToggleDOBOT">
<MudText Typo="Typo.subtitle1">DOBOT</MudText>
<MudIcon Icon="@(IsDobotExpanded ? 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="@DobotMudColor" />
<div>
<MudText Typo="Typo.caption">@DobotStatus.ToUpper()</MudText>
<MudText Typo="Typo.caption" Style="color:#9a9a9a;">
Code: @State.Imr.CodeDobotStatus_Opc &nbsp;|&nbsp; @DobotStatusCodeText
</MudText>
</div>
</div>
<div class="mt-1 mb-1">
<MudButton FullWidth="true" Variant="Variant.Outlined" Color="Color.Error" Size="Size.Small" OnClick="Dobot_Cancel" Disabled="@(!State.CanControl)">Cancel</MudButton>
</div>
@if (IsDobotExpanded)
{
<MudText Typo="Typo.caption" Class="sec-title mt-2">Control</MudText>
<div class="op-grid">
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Dobot_Home" Disabled="@DobotLocked("GoHome")">Home</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Dobot_Continue" Disabled="@DobotLocked("Continue")">Continue</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Dobot_PowerOn" Disabled="@DobotLocked("PowerOn")">PowerOn</MudButton>
</div>
<MudText Typo="Typo.caption" Class="sec-title mt-2">Pick</MudText>
<div class="op-grid">
<MudNumericField T="int?" @bind-Value="okCount" Placeholder="OK" Variant="Variant.Outlined" Class="pnl-num" Min="0" Max="99" />
<MudNumericField T="int?" @bind-Value="ngCount" Placeholder="NG" Variant="Variant.Outlined" Class="pnl-num" Min="0" Max="99" />
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="PickUp_Vda" Disabled="@ImrLocked("PickUp")">Pick Up</MudButton>
</div>
}
</MudPaper>
@code {
[Inject] StateService State { get; set; } = default!;
[Inject] CommandService Cmd { get; set; } = default!;
bool IsDobotExpanded = true;
void ToggleDOBOT() => IsDobotExpanded = !IsDobotExpanded;
int? okCount;
int? ngCount;
protected override async Task OnInitializedAsync()
{
await State.StartAsync();
State.ImrChanged += Refresh; // DobotStatus comes from IMR state
State.WorkflowChanged += Refresh;
}
public ValueTask DisposeAsync()
{
State.ImrChanged -= Refresh;
State.WorkflowChanged -= Refresh;
return ValueTask.CompletedTask;
}
private void Refresh() => InvokeAsync(StateHasChanged);
private string DobotStatus
{
get
{
var s = State.Imr.DobotStatus_Opc?.ToLower() ?? "";
var e = State.Imr.CodeDobotStatus_Opc;
if (e == 9999) return "off";
if (e != 0) return "error";
if (s.Contains("error") || s.Contains("fault")) return "error";
if (s.Contains("controlling") || s.Contains("move")) return "moving";
if (s.Contains("canceled")) return "canceled";
if (s.Contains("finished") || s.Contains("idle")) return "ok";
return "ok";
}
}
private Color DobotMudColor => DobotStatus switch
{
"ok" => Color.Success,
"idle" => Color.Success,
"moving" => Color.Info,
"canceled" => Color.Warning,
"error" => Color.Error,
_ => Color.Default
};
private string DobotStatusCodeText => State.Imr.CodeDobotStatus_Opc switch
{
0 => "Dobot Waiting",
98 => "Dobot Waiting for Connection",
99 => "Dobot Reconnecting",
100 => "Dobot Running",
101 => "Dobot Disconnected",
102 => "Dobot No Data Received",
103 => "Dobot Data Not Updated",
104 => "Dobot Target Coordinates Out of Range",
105 => "Dobot Returning Home",
106 => "Dobot Checking Emergency Stop Button",
107 => "Dobot in Alarm State",
108 => "Dobot Powering On, Waiting",
109 => "Dobot Powered On",
110 => "Dobot in Drag Mode",
111 => "Dobot Waiting: Select Continue or Return Home",
112 => "Dobot OK Count Limit Reached",
113 => "Dobot NG Count Limit Reached",
999 => "Dobot Error",
_ => "Unknown"
};
// Dobot queue locking
private bool DobotLocked(string label)
=> !State.CanControl || State.Workflow.DobotBusyLabel == label || State.Workflow.DobotNextLabel == label;
// PickUp goes through the IMR queue
private bool ImrLocked(string label)
=> !State.CanControl || State.Workflow.ImrBusyLabel == label || State.Workflow.ImrNextLabel == label;
private Task Dobot_Cancel() => Cmd.DobotCancelAsync();
private Task Dobot_Home() => Cmd.DobotGoHomeAsync();
private Task Dobot_Continue() => Cmd.DobotContinueAsync();
private Task Dobot_PowerOn() => Cmd.DobotPowerOnAsync();
private Task PickUp_Vda() => Cmd.ImrPickupAsync(okCount ?? 0, ngCount ?? 0);
}
<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; }
</style>

View File

@@ -0,0 +1,320 @@
@implements IAsyncDisposable
<MudPaper Elevation="0" Class="pa-2" Style="background:transparent;">
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center"
Style="cursor:pointer" @onclick="ToggleExpand">
<MudText Typo="Typo.subtitle1">OPERATIONS</MudText>
<MudIcon Icon="@(_expanded ? Icons.Material.Filled.ExpandMore : Icons.Material.Filled.ExpandLess)" Size="Size.Small" />
</MudStack>
@if (IsLockBlocked)
{
<div style="background:rgba(255,100,0,0.08);border:1px solid rgba(255,100,0,0.25);border-radius:5px;padding:4px 8px;margin-bottom:4px;">
<MudText Typo="Typo.caption" Style="color:#f90;">@Lang.T("Bạn chưa giữ quyền điều khiển. Vào CONTROL ACCESS → ACQUIRE CONTROL.", "You don't hold control. Go to CONTROL ACCESS → ACQUIRE CONTROL.")</MudText>
</div>
}
<MudButton Variant="Variant.Outlined" Color="Color.Error" Size="Size.Small"
FullWidth="true" Class="my-1"
OnClick="HardCancel"
Disabled="@(!IsAnyRunning && _opQueue.Count == 0)">
<MudIcon Icon="@Icons.Material.Filled.Stop" Size="Size.Small" /> Cancel @(_opQueue.Count > 0 ? $"+{_opQueue.Count}" : "")
</MudButton>
@if (_expanded)
{
<MudText Typo="Typo.caption" Class="sec-title mt-2">Params</MudText>
<div class="op-grid-4 mb-2">
<MudNumericField T="int?" @bind-Value="_times" Placeholder="OK" Variant="Variant.Outlined" Class="pnl-num" Min="1" Max="99" />
<MudNumericField T="int?" @bind-Value="_ng" Placeholder="NG" Variant="Variant.Outlined" Class="pnl-num" Min="0" Max="99" />
<MudButton Variant="Variant.Filled" Color="Color.Success" Size="Size.Small"
StartIcon="@Icons.Material.Filled.PlayArrow" OnClick="RunAll"
Disabled="@(IsAnyRunning || IsLockBlocked)"></MudButton>
<MudButton Variant="Variant.Outlined" Color="Color.Success" Size="Size.Small"
OnClick="RunSelected"
Disabled="@(_selectedSteps.Count == 0 || IsAnyRunning || IsLockBlocked)">[@_selectedSteps.Count]</MudButton>
</div>
<MudText Typo="Typo.caption" Class="sec-title">Steps</MudText>
<div class="op-grid-3">
<MudButton Variant="Variant.Outlined" Color="Color.Warning" Size="Size.Small"
OnClick='() => RunOp("HomeRb", ct => Cmd.WorkflowHomeRbAsync(ct))'
Disabled="@(IsAnyRunning || IsLockBlocked)">Home All</MudButton>
@OpCard(1, "Init")
@OpCard(2, "C2 AMR")
@OpCard(3, "→ Cap1")
@OpCard(4, "C:AMR→IMR")
@OpCard(5, "→ABB:PINKUP")
@OpCard(6, "C:IMR→AMR")
@OpCard(7, "→ Cap2")
@OpCard(8, "AMR C2")
</div>
}
</MudPaper>
@code {
[Inject] StateService State { get; set; } = default!;
[Inject] CommandService Cmd { get; set; } = default!;
[Inject] ISnackbar Snackbar { get; set; } = default!;
[Inject] HttpClient Http { get; set; } = default!;
[Inject] LangService Lang { get; set; } = default!;
[Inject] ScriptLogService Log { get; set; } = default!;
private bool _expanded = true;
private void ToggleExpand() => _expanded = !_expanded;
private int? _times, _ng;
private int _prevCycles = -1;
private string _myUserId = "";
// True when using real stack and lock state shows we don't hold workflow lock
private bool IsLockBlocked =>
!State.System.IsSimulation
&& State.LockState is not null
&& (State.LockState.Workflow is null || State.LockState.Workflow.UserId != _myUserId);
private readonly HashSet<string> _runningOps = new();
private readonly Queue<(string Name, Func<CancellationToken, Task> Action)> _opQueue = new();
private CancellationTokenSource? _cts;
private bool _queueRunning;
private readonly List<int> _selectedSteps = new();
private bool IsAnyRunning => _queueRunning || State.Workflow.IsRunning;
private bool IsRunning(string k) => _runningOps.Contains(k);
private bool IsQueued(string k) => _opQueue.Any(q => q.Name == k);
private void ToggleStep(int n)
{
if (!_selectedSteps.Remove(n)) _selectedSteps.Add(n);
}
private Task ExecStep(int n, CancellationToken ct) => n switch
{
1 => Cmd.FlowStepInitAsync(ct),
2 => Cmd.FlowStepLoadC2Async(ct),
3 => Cmd.FlowStepToCap1Async(ct),
4 => Cmd.FlowStepAmrToImrAsync(ct),
5 => Cmd.FlowStepProcessAsync(_times ?? 1, _ng ?? 0, ct),
6 => Cmd.FlowStepImrToAmrAsync(ct),
7 => Cmd.FlowStepToCap2Async(ct),
8 => Cmd.FlowStepUnloadC2Async(ct),
_ => Task.CompletedTask
};
private RenderFragment OpCard(int num, string name) => __builder =>
{
var key = $"step{num}";
bool running = IsRunning(key);
bool queued = IsQueued(key);
int selIdx = _selectedSteps.IndexOf(num);
bool sel = selIdx >= 0;
var color = running ? Color.Primary : sel ? Color.Success : Color.Default;
var variant = (running || sel) ? Variant.Filled : Variant.Outlined;
<MudButton Variant="@variant" Color="@color" Size="Size.Small"
Disabled="@(IsAnyRunning)"
Style="@(queued ? "opacity:0.55;border-style:dashed;" : "")"
OnClick="() => { if (!IsAnyRunning) ToggleStep(num); }">
@if (sel && !running)
{
<span class="sel-n">@(selIdx + 1)</span>
}
@(running ? "…" : name)
</MudButton>
};
protected override async Task OnInitializedAsync()
{
await State.StartAsync();
State.WorkflowChanged += OnWorkflowChanged;
State.LockStateChanged += OnLockChanged;
Lang.LangChanged += OnLockChanged;
try
{
var me = await Http.GetFromJsonAsync<MeWfDto>("/api/auth/me");
_myUserId = me?.UserId ?? "";
}
catch { }
}
public ValueTask DisposeAsync()
{
State.WorkflowChanged -= OnWorkflowChanged;
State.LockStateChanged -= OnLockChanged;
Lang.LangChanged -= OnLockChanged;
HardCancel();
return ValueTask.CompletedTask;
}
private void OnWorkflowChanged()
{
var cycles = State.Workflow.CompletedCycles;
if (_prevCycles >= 0 && cycles > _prevCycles)
Snackbar.Add(Lang.T($"Hoàn thành chu kỳ {cycles}", $"Completed cycle {cycles}"), Severity.Success);
_prevCycles = cycles;
InvokeAsync(StateHasChanged);
}
private void OnLockChanged() => InvokeAsync(StateHasChanged);
record MeWfDto(string? UserId);
private void RunAll()
{
_selectedSteps.Clear();
WarnStep(1); // online check
EnqueueOp("Run All", ct => Cmd.WorkflowRunCycleAsync(_times ?? 1, _ng ?? 0, ct));
}
private void RunSelected()
{
if (_selectedSteps.Count == 0 || IsAnyRunning) return;
var steps = _selectedSteps.ToList();
_selectedSteps.Clear();
foreach (var n in steps) WarnStep(n);
EnqueueOp("Run Sel", async ct =>
{
foreach (var n in steps)
{
ct.ThrowIfCancellationRequested();
await ExecStep(n, ct);
}
});
}
private void RunOp(string n, Func<CancellationToken, Task> a) => EnqueueOp(n, a);
// ── Position detection (mirrors SystemCondition server-side logic) ───────────
private static bool Near(double x, double y, double tx, double ty) =>
Math.Abs(x - tx) < RobotPositions.POS_TOL &&
Math.Abs(y - ty) < RobotPositions.POS_TOL;
private bool ImrAtC1 => Near(State.Imr.X, State.Imr.Y, RobotPositions.IMR_C1_X, RobotPositions.IMR_C1_Y);
private bool AmrAtCap1 => Near(State.Amr.X, State.Amr.Y, RobotPositions.AMR_CAP1_X, RobotPositions.AMR_CAP1_Y);
private bool AmrAtCap2 => Near(State.Amr.X, State.Amr.Y, RobotPositions.AMR_CAP2_X, RobotPositions.AMR_CAP2_Y);
/// <summary>Ghi cảnh báo ra log + snackbar nếu pre-condition của step chưa đạt.</summary>
private void WarnStep(int n)
{
if (!State.Imr.IsOnline)
PosWarn("IMR", "offline", Lang.T("Kiểm tra kết nối IMR", "Check IMR connection"));
if (!State.Amr.IsOnline)
PosWarn("AMR", "offline", Lang.T("Kiểm tra kết nối AMR", "Check AMR connection"));
switch (n)
{
case 2: // C2 AMR — AMR cần ở Cap2
if (!AmrAtCap2)
PosWarn("AMR", Lang.T("chưa ở Cap2", "not at Cap2"),
Lang.T("→ chạy Step 1 Init trước", "→ run Step 1 Init first"));
break;
case 3: // → Cap1 — AMR cần ở Cap2 để undock
if (!AmrAtCap2)
PosWarn("AMR", Lang.T("chưa ở Cap2", "not at Cap2"),
Lang.T("→ chạy Step 1 Init hoặc Step 8 trước", "→ run Step 1 Init or Step 8 first"));
break;
case 4: // C:AMR→IMR — IMR@C1 + AMR@Cap1
if (!ImrAtC1)
PosWarn("IMR", Lang.T("chưa ở C1", "not at C1"),
Lang.T("→ chạy Step 1 Init trước", "→ run Step 1 Init first"));
if (!AmrAtCap1)
PosWarn("AMR", Lang.T("chưa ở Cap1", "not at Cap1"),
Lang.T("→ chạy Step 3 → Cap1 trước", "→ run Step 3 → Cap1 first"));
break;
case 5: // ABB:PICKUP — IMR cần ở C1 trước khi undock
if (!ImrAtC1)
PosWarn("IMR", Lang.T("chưa ở C1", "not at C1"),
Lang.T("→ chạy Step 1 Init trước", "→ run Step 1 Init first"));
break;
case 6: // C:IMR→AMR — IMR@C1 + AMR@Cap1
if (!ImrAtC1)
PosWarn("IMR", Lang.T("chưa ở C1", "not at C1"),
Lang.T("→ chạy Step 1 Init trước", "→ run Step 1 Init first"));
if (!AmrAtCap1)
PosWarn("AMR", Lang.T("chưa ở Cap1", "not at Cap1"),
Lang.T("→ chạy Step 4 C:AMR→IMR hoặc Step 3 trước", "→ run Step 4 or Step 3 first"));
break;
case 7: // → Cap2 — AMR cần ở Cap1 để undock
if (!AmrAtCap1)
PosWarn("AMR", Lang.T("chưa ở Cap1", "not at Cap1"),
Lang.T("→ chạy Step 3 → Cap1 trước", "→ run Step 3 → Cap1 first"));
break;
case 8: // AMR C2 — AMR cần ở Cap2
if (!AmrAtCap2)
PosWarn("AMR", Lang.T("chưa ở Cap2", "not at Cap2"),
Lang.T("→ chạy Step 7 → Cap2 trước", "→ run Step 7 → Cap2 first"));
break;
}
}
private void PosWarn(string device, string condition, string guide) =>
Log.Log(LogFormat.Line(LogFormat.CWarn, "WARN", device, condition, guide));
private void EnqueueOp(string name, Func<CancellationToken, Task> action)
{
if (IsAnyRunning || IsQueued(name)) return;
_opQueue.Enqueue((name, action));
if (!_queueRunning)
{
_cts?.Dispose();
_cts = new CancellationTokenSource();
_ = RunQueueAsync(_cts.Token);
}
}
private void HardCancel()
{
_opQueue.Clear();
_cts?.Cancel();
_ = Cmd.WorkflowEmergencyStopAsync();
}
private async Task RunQueueAsync(CancellationToken token)
{
_queueRunning = true;
try
{
while (_opQueue.Count > 0 && !token.IsCancellationRequested)
{
(string name, Func<CancellationToken, Task> action)? item = null;
await InvokeAsync(() => { if (_opQueue.Count > 0) item = _opQueue.Dequeue(); });
if (item == null) break;
await ExecAsync(item.Value.name, item.Value.action, token);
}
}
finally { _queueRunning = false; await InvokeAsync(StateHasChanged); }
}
private async Task ExecAsync(string name, Func<CancellationToken, Task> action, CancellationToken token)
{
await InvokeAsync(() => { _runningOps.Add(name); StateHasChanged(); });
try
{
await action(token);
await InvokeAsync(StateHasChanged);
}
catch (OperationCanceledException) { }
catch { _ = Cmd.WorkflowEmergencyStopAsync(); }
finally { await InvokeAsync(() => { _runningOps.Remove(name); StateHasChanged(); }); }
}
}
<style>
.sec-title { display:block; color:#9CA3AF; margin-bottom:4px; }
.op-grid-4 { display:grid; grid-template-columns:repeat(4, 1fr); gap:5px; }
.op-grid-3 { display:grid; grid-template-columns:repeat(3, 1fr); gap:5px; }
.op-grid-2 { display:grid; grid-template-columns:1fr 1fr; gap:5px; }
.mt-1 { margin-top:5px; }
.sel-n { display:inline-flex; align-items:center; justify-content:center;
width:14px; height:14px; border-radius:50%;
background:rgba(0,0,0,0.25); font-size:9px; font-weight:900;
margin-right:4px; flex-shrink:0; }
</style>

View File

@@ -0,0 +1,224 @@
@page "/"
@page "/{Username}"
@rendermode @(new InteractiveWebAssemblyRenderMode(prerender: false))
@implements IAsyncDisposable
@inject HttpClient Http
@inject ISnackbar Snackbar
@inject LangService Lang
<MudThemeProvider IsDarkMode="true" />
<MudPopoverProvider />
<MudDialogProvider />
<MudSnackbarProvider />
<NotificationProvider Muted="@_notifMuted" />
<div class="right-top">
<div class="right-header">
<div style="display:flex;align-items:center;gap:6px;">
@if (!string.IsNullOrEmpty(_username))
{
<span style="font-size:11px;color:#444;font-weight:500;">@_username</span>
}
</div>
<div class="mode-toggle">
<MudTooltip Text="@Lang.T("Tài khoản của tôi", "My Account")" Placement="Placement.Bottom">
<MudIconButton Icon="@Icons.Material.Filled.AccountCircle"
Size="Size.Small" Style="color:#aaa;padding:4px;" Href="/profile" />
</MudTooltip>
@if (_isManager)
{
<MudTooltip Text="App Settings — Quản lý tài khoản" Placement="Placement.Bottom">
<MudIconButton Icon="@Icons.Material.Filled.AdminPanelSettings"
Size="Size.Small" Style="color:#aaa;padding:4px;" Href="/users" />
</MudTooltip>
}
@* SIM / REAL toggle — chỉ hiện khi tài khoản có quyền real *@
@if (_canUseReal)
{
<MudTooltip Text="@(_useReal ? Lang.T("Đang dùng Real — nhấn để chuyển Sim", "Using Real — click to switch to Sim") : Lang.T("Đang dùng Sim — nhấn để chuyển Real", "Using Sim — click to switch to Real"))"
Placement="Placement.Bottom">
<MudChip T="string"
Color="@(_useReal ? Color.Warning : Color.Info)"
Size="Size.Small"
Style="cursor:pointer;height:24px;font-size:11px;font-weight:700;padding:0 8px;"
OnClick="ToggleStack">
@(_useReal ? "REAL" : "SIM")
</MudChip>
</MudTooltip>
}
else
{
<span style="font-size:11px;font-weight:700;color:#3a7bbf;padding:0 6px;opacity:0.7;">SIM</span>
}
<MudTooltip Text="@(_notifMuted ? Lang.T("Thông báo đang tắt", "Notifications Off") : Lang.T("Thông báo đang bật", "Notifications On"))" Placement="Placement.Bottom">
<MudIconButton Icon="@(_notifMuted ? Icons.Material.Filled.NotificationsOff : Icons.Material.Filled.Notifications)"
Size="Size.Small" OnClick="ToggleNotif"
Style="@(_notifMuted ? "color:#444;padding:4px;" : "color:#f0c040;padding:4px;")" />
</MudTooltip>
<MudTooltip Text="@Lang.T("Đăng xuất", "Logout")" Placement="Placement.Bottom">
<form method="post" action="/auth/do-logout" style="margin:0;display:inline;">
<MudIconButton ButtonType="ButtonType.Submit" Icon="@Icons.Material.Filled.Logout"
Size="Size.Small" Style="color:#666;padding:4px;" />
</form>
</MudTooltip>
</div>
</div>
<StatusPanel />
</div>
@{ var wfBlocker = WfBlocker; }
@if (wfBlocker is not null)
{
<div class="wf-block-banner">
<MudIcon Icon="@Icons.Material.Filled.Bolt" Size="Size.Small" Style="flex-shrink:0;" />
<span style="font-weight:800;letter-spacing:.4px;">WORKFLOW MODE</span>
<span class="wf-block-sep">—</span>
<strong style="color:#ffe082;">@wfBlocker.Name</strong>
<span class="wf-block-note">@Lang.T("đang điều khiển · Bạn không thể thao tác", "is controlling · You cannot perform actions")</span>
</div>
}
<div id="right-scroll" class="right-scroll @(wfBlocker is not null ? "panels-blocked" : "")">
<div id="p-ctrl" class="panel-card"><ControlPanel /></div>
@if (!State.System.IsSimulation || _isManager)
{
<div id="p-lock" class="panel-card"><LockPanel UseReal="@_useReal" MyUserId="@_userId" MyRole="@_role"
CanWorkflow="@(_isManager || _canWorkflow)"
CanManual="@(_isManager || (_canUseReal && !_canWorkflow))" /></div>
}
<div id="p-ops" class="panel-card"><FlowPhasePanel /></div>
<div id="p-conveyor" class="panel-card"><ConveyorSectionPanel /></div>
<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>
@code {
[Parameter] public string? Username { get; set; }
[Inject] StateService State { get; set; } = default!;
bool _notifMuted = true;
bool _isManager = false;
bool _canUseReal = false;
bool _canWorkflow = false;
bool _useReal = false;
bool _stackBusy = false;
string _username = "";
string _userId = "";
string _role = "";
protected override async Task OnInitializedAsync()
{
await State.StartAsync();
State.SystemChanged += Refresh;
State.LockStateChanged += Refresh;
State.StackChanged += OnStackChanged;
Lang.LangChanged += Refresh;
await Lang.LoadAsync(Http);
try
{
var me = await Http.GetFromJsonAsync<MeDto>("/api/auth/me");
_isManager = me?.Role is "Manager" or "Admin";
_username = me?.Username ?? Username ?? "";
_canUseReal = me?.CanUseReal == true;
_canWorkflow = me?.CanWorkflow == true;
_useReal = me?.UseReal == true;
_userId = me?.UserId ?? "";
_role = me?.Role ?? "";
}
catch { }
try
{
var prefs = await Http.GetFromJsonAsync<PrefsDto>("/api/prefs");
if (prefs is not null) _notifMuted = prefs.NotifMuted;
// Lang already loaded via Lang.LoadAsync above
}
catch { }
}
private async Task ToggleStack()
{
if (_stackBusy || !_canUseReal) return;
_stackBusy = true;
try
{
bool newUseReal = !_useReal;
var url = newUseReal ? "/api/mode/real" : "/api/mode/simulation";
var resp = await Http.PostAsync(url, null);
if (resp.IsSuccessStatusCode)
{
_useReal = newUseReal;
await State.SwitchStackAsync(newUseReal);
}
}
catch { }
finally
{
_stackBusy = false;
}
}
private void Refresh() => InvokeAsync(StateHasChanged);
private void OnStackChanged(bool useReal)
{
_useReal = useReal;
InvokeAsync(StateHasChanged);
}
public ValueTask DisposeAsync()
{
State.SystemChanged -= Refresh;
State.LockStateChanged -= Refresh;
State.StackChanged -= OnStackChanged;
Lang.LangChanged -= Refresh;
return ValueTask.CompletedTask;
}
/// <summary>Workflow lock holder khi KHÔNG phải mình — cần hiện banner cảnh báo.</summary>
LockHolderDto? WfBlocker =>
!State.System.IsSimulation && State.LockState?.Workflow is { } h && h.UserId != _userId ? h : null;
private async Task ToggleLang() => await Lang.ToggleAsync(Http);
private async Task ToggleNotif()
{
_notifMuted = !_notifMuted;
try { await Http.PutAsJsonAsync("/api/prefs", new { Lang = (string?)null, NotifMuted = (bool?)_notifMuted }); }
catch { }
}
record MeDto(string Role, string Username, bool CanUseReal, bool UseReal, string? UserId, bool CanWorkflow);
record PrefsDto(string Lang, bool NotifMuted);
}
<style>
.right-top { flex-shrink:0; padding:12px 12px 0; background:#27292b; border-bottom:1px solid rgba(255,255,255,0.06); padding-bottom:8px; }
.right-scroll { flex:1; overflow-y:auto; padding:10px 12px 12px; height:0; scrollbar-width:none; background:#27292b; }
.right-scroll::-webkit-scrollbar { display:none; }
.right-header { display:flex; justify-content:space-between; align-items:center; padding-bottom:8px; margin-bottom:8px; border-bottom:1px solid rgba(255,255,255,0.08); }
.mode-toggle { display:flex; gap:4px; align-items:center; }
/* ── Workflow block banner ── */
.wf-block-banner {
display: flex; align-items: center; gap: 7px;
padding: 7px 14px;
background: rgba(243,156,18,0.13);
border-bottom: 1px solid rgba(243,156,18,0.4);
color: #f39c12; font-size: 11px; font-weight: 600;
flex-shrink: 0;
}
.wf-block-sep { opacity: 0.5; }
.wf-block-note { margin-left: auto; font-weight: 400; opacity: 0.75; font-size: 10px; }
/* dim all panels when someone else holds workflow */
.panels-blocked .panel-card { opacity: 0.45; pointer-events: none; }
/* but keep LockPanel interactive so user can see status / join queue */
.panels-blocked #p-lock { opacity: 1; pointer-events: auto; }
.panel-card { background:rgba(255,255,255,0.02); border:1px solid rgba(255,255,255,0.07); border-radius:8px; margin-bottom:8px; }
</style>

View File

@@ -0,0 +1,86 @@
@implements IAsyncDisposable
<div class="ias-3col">
@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)"
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>
</div>
</div>
@code {
[Inject] StateService State { get; set; } = default!;
protected override async Task OnInitializedAsync()
{
await State.StartAsync();
State.ImrChanged += Refresh;
State.AmrChanged += Refresh;
State.AsrsChanged += Refresh;
State.WorkflowChanged += Refresh;
}
public ValueTask DisposeAsync()
{
State.ImrChanged -= Refresh;
State.AmrChanged -= Refresh;
State.AsrsChanged -= Refresh;
State.WorkflowChanged -= Refresh;
return ValueTask.CompletedTask;
}
private void Refresh() => InvokeAsync(StateHasChanged);
private RenderFragment RobotRow(string label, RobotStateDto s) => __builder =>
{
bool online = s.IsOnline;
bool ready = s.NewBaseRequest == true;
<div class="ias-row">
<MudChip T="string" Size="Size.Small" Color="@(online ? Color.Success : Color.Default)"
Variant="Variant.Text" Style="height:22px;font-size:11px;margin:0;flex-shrink:0;">@label</MudChip>
<MudChip T="string" Size="Size.Small"
Color="@(ready ? Color.Success : Color.Default)"
Variant="@(ready ? Variant.Filled : Variant.Outlined)"
Style="height:22px;font-size:11px;margin:0;flex-shrink:0;">NBR</MudChip>
<span class="@(online ? "ias-pos" : "ias-pos ias-dim")">@($"{s.X:F1}, {s.Y:F1}")</span>
@foreach (var a in s.Actions.Take(2))
{
string acls = a.ActionStatus switch {
"RUNNING" => "ias-act-run",
"WAITING" or "INITIALIZING" => "ias-act-wait",
"FINISHED" => "ias-act-done",
"FAILED" or "ABORTED" => "ias-act-fail",
_ => "ias-act-idle"
};
string aname = string.Equals(a.ActionID, "UndockFromStation", StringComparison.OrdinalIgnoreCase)
? "Undock" : (a.ActionID ?? "?");
<span class="ias-act @acls">@aname</span>
}
@if (s.Errors.Any())
{
<span class="ias-err">
<MudIcon Icon="@Icons.Material.Filled.Warning" Size="Size.Small" /> @string.Join(", ", s.Errors)
</span>
}
</div>
};
}
<style>
.ias-3col { display:grid; grid-template-columns:1fr 1fr auto; gap:4px 8px; align-items:center; }
.ias-row { display:flex; gap:4px; align-items:center; flex-wrap:nowrap; overflow:hidden; min-width:0; }
.ias-pos { font-size:11px; color:#F1F5F9; font-variant-numeric:tabular-nums; white-space:nowrap; flex-shrink:0; }
.ias-dim { color:#9CA3AF; }
.ias-act { font-size:10px; font-weight:600; padding:1px 5px; border-radius:4px; border:1px solid; white-space:nowrap; flex-shrink:0; }
.ias-act-run { color:#4a9eff; border-color:rgba(74,158,255,0.5); background:rgba(74,158,255,0.08); }
.ias-act-wait { color:#f39c12; border-color:rgba(243,156,18,0.45); background:rgba(243,156,18,0.06); }
.ias-act-done { color:#2ecc71; border-color:rgba(46,204,113,0.25); background:transparent; }
.ias-act-fail { color:#e74c3c; border-color:rgba(231,76,60,0.45); background:rgba(231,76,60,0.07); }
.ias-act-idle { color:#9CA3AF; border-color:#1c1c1c; background:transparent; }
.ias-err { font-size:10px; color:#e74c3c; white-space:nowrap; overflow:hidden; text-overflow:ellipsis; }
</style>

View File

@@ -0,0 +1,226 @@
@using Lab505.Shared
@implements IAsyncDisposable
<MudPaper Elevation="0" Class="pa-3" Style="background:transparent;">
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center"
Style="cursor:pointer" @onclick="ToggleExpand">
<MudText Typo="Typo.subtitle1">IMR</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.ToUpper()</MudText>
<MudText Typo="Typo.caption" Style="color:#9a9a9a;">
Errors: @(State.Imr.Errors is { Count: > 0 } errors ? string.Join(", ", errors) : "none")
</MudText>
</div>
</div>
<div class="mt-1 mb-1">
<MudButton FullWidth="true" Variant="Variant.Outlined" Color="Color.Error" Size="Size.Small" OnClick="Cancel" Disabled="@(!State.CanControl)">Cancel</MudButton>
</div>
@if (_expanded)
{
<MudText Typo="Typo.caption" Class="sec-title mt-2">Move</MudText>
<div class="op-grid-2">
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="MoveToC1" Disabled="@IsLocked("MoveTo Bt1")">C1</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="MoveToAbb" Disabled="@IsLocked("MoveTo Abb")">ABB</MudButton>
</div>
<MudText Typo="Typo.caption" Class="sec-title mt-2">Action</MudText>
<div class="op-grid-2">
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Load" Disabled="@IsLocked("Load")">Load</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Unload" Disabled="@IsLocked("Unload")">Unload</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="UndockFromC1" Disabled="@IsLocked("Undock")">MS@(RobotPositions.IMR_UNDOCK_C1)m</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="UndockFromAbb" Disabled="@IsLocked("Undock")">MS@(RobotPositions.IMR_UNDOCK_ABB)m</MudButton>
</div>
<MudText Typo="Typo.caption" Class="sec-title mt-2">NAV</MudText>
<div class="op-grid">
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Resume">Resume</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Pause">Pause</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" OnClick="Reset">Reset</MudButton>
</div>
<div class="op-grid-4 mt-2">
<MudNumericField T="double?" @bind-Value="_poseX" Placeholder="X" Variant="Variant.Outlined"
Format="F3" Step="0.01" Culture="@System.Globalization.CultureInfo.InvariantCulture"
HideSpinButtons="true" Class="pnl-num" />
<MudNumericField T="double?" @bind-Value="_poseY" Placeholder="Y" Variant="Variant.Outlined"
Format="F3" Step="0.01" Culture="@System.Globalization.CultureInfo.InvariantCulture"
HideSpinButtons="true" Class="pnl-num" />
<MudNumericField T="double?" @bind-Value="_poseYaw" Placeholder="Yaw" Variant="Variant.Outlined"
Format="F3" Step="0.01" Culture="@System.Globalization.CultureInfo.InvariantCulture"
HideSpinButtons="true" Class="pnl-num" />
<MudButton Variant="Variant.Outlined" Size="Size.Small" Color="Color.Warning"
StartIcon="@(_settingPose ? Icons.Material.Filled.HourglassBottom : null)"
OnClick="RunInitPose" Disabled="@(_settingPose || !State.CanControl)">
@(_settingPose ? "..." : "InitPose")
</MudButton>
</div>
}
</MudPaper>
@code {
[Inject] StateService State { get; set; } = default!;
[Inject] CommandService Cmd { get; set; } = default!;
[Inject] ISnackbar Snackbar { get; set; } = default!;
[Inject] LangService Lang { get; set; } = default!;
private bool _expanded = true;
private double? _poseX;
private double? _poseY;
private double? _poseYaw;
private bool _settingPose;
private CancellationTokenSource? _initPoseCts;
protected override async Task OnInitializedAsync()
{
await State.StartAsync();
State.ImrChanged += Refresh;
State.WorkflowChanged += Refresh;
Lang.LangChanged += Refresh;
}
public ValueTask DisposeAsync()
{
State.ImrChanged -= Refresh;
State.WorkflowChanged -= Refresh;
Lang.LangChanged -= Refresh;
CancelInitPose();
_initPoseCts?.Dispose();
_initPoseCts = null;
return ValueTask.CompletedTask;
}
private void ToggleExpand() => _expanded = !_expanded;
private void Refresh() => InvokeAsync(StateHasChanged);
private string StatusText
{
get
{
var imr = State.Imr;
if (!imr.IsOnline) return "off";
if (imr.Errors.Count > 0) return "error";
if (imr.NewBaseRequest == false) return "moving";
return "ok";
}
}
private Color StatusColor => StatusText switch
{
"ok" => Color.Success,
"moving" => Color.Info,
"error" => Color.Error,
_ => Color.Default
};
private bool IsLocked(string label)
=> !State.CanControl || State.Workflow.ImrBusyLabel == label || State.Workflow.ImrNextLabel == label;
private static bool IsNear(double x, double y, double targetX, double targetY)
=> Math.Abs(x - targetX) < RobotPositions.POS_TOL && Math.Abs(y - targetY) < RobotPositions.POS_TOL;
private bool IsDocked()
{
var imr = State.Imr;
return IsNear(imr.X, imr.Y, RobotPositions.IMR_C1_X, RobotPositions.IMR_C1_Y)
|| IsNear(imr.X, imr.Y, RobotPositions.IMR_ABB_X, RobotPositions.IMR_ABB_Y);
}
private bool WarnIfDocked()
{
if (!IsDocked() || State.Workflow.ImrCmd == "undocking")
return false;
Snackbar.Add(
Lang.T("IMR đang docked — lùi trước khi di chuyển!", "IMR is docked — undock before moving!"),
Severity.Warning);
return true;
}
private Task MoveToC1() => WarnIfDocked() ? Task.CompletedTask : Cmd.ImrMoveToAsync("Bt1");
private Task MoveToAbb() => WarnIfDocked() ? Task.CompletedTask : Cmd.ImrMoveToAsync("Abb");
private Task UndockFromC1() => Cmd.ImrUndockAsync(-RobotPositions.IMR_UNDOCK_C1, RobotPositions.IMR_UNDOCK_VEL);
private Task UndockFromAbb() => Cmd.ImrUndockAsync(-RobotPositions.IMR_UNDOCK_ABB, RobotPositions.IMR_UNDOCK_VEL);
private Task Load() => Cmd.ImrLoadAsync();
private Task Unload() => Cmd.ImrUnloadAsync();
private Task Resume() => Cmd.ImrResumeAsync();
private Task Pause() => Cmd.ImrPauseAsync();
private Task Reset() => Cmd.ImrResetOpcAsync();
private Task Cancel()
{
CancelInitPose();
_settingPose = false;
StateHasChanged();
return Cmd.ImrCancelAsync();
}
private async Task RunInitPose()
{
_initPoseCts?.Dispose();
_initPoseCts = new CancellationTokenSource();
var ct = _initPoseCts.Token;
_settingPose = true;
await InvokeAsync(StateHasChanged);
try
{
var targetX = _poseX ?? 0;
var targetY = _poseY ?? 0;
var targetTheta = _poseYaw ?? 0;
// VDA initPosition instant action (thay cho OPC UA InitialPose)
await Cmd.ImrInitPositionAsync(targetX, targetY, targetTheta, ct);
Snackbar.Add(
Lang.T(
$"Đã gửi InitPosition ({targetX:F2}, {targetY:F2}, {targetTheta:F2})",
$"InitPosition sent ({targetX:F2}, {targetY:F2}, {targetTheta:F2})"),
Severity.Success);
}
catch (OperationCanceledException)
{
Snackbar.Add(Lang.T("InitPosition đã huỷ", "InitPosition cancelled"), Severity.Info);
}
finally
{
_settingPose = false;
_initPoseCts?.Dispose();
_initPoseCts = null;
await InvokeAsync(StateHasChanged);
}
}
private void CancelInitPose()
{
try
{
_initPoseCts?.Cancel();
}
catch
{
}
}
}
<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:1fr 1fr; gap:5px; }
.op-grid-4 { display:grid; grid-template-columns:repeat(4, 1fr); gap:5px; }
</style>

View File

@@ -0,0 +1,404 @@
@implements IAsyncDisposable
@inject HttpClient Http
@inject StateService State
@inject ISnackbar Snackbar
@inject LangService Lang
<MudPaper Elevation="0" Class="pa-2" Style="background:transparent;">
<MudStack Row="true" Justify="Justify.SpaceBetween" AlignItems="AlignItems.Center"
Style="cursor:pointer" @onclick="ToggleExpand">
<MudText Typo="Typo.subtitle1">CONTROL ACCESS</MudText>
<div style="display:flex;align-items:center;gap:6px;">
@if (IsManager)
{
<a href="/users" @onclick:stopPropagation="true"
style="font-size:10px;color:#4a9eff;text-decoration:none;opacity:0.8;display:flex;align-items:center;gap:2px;"
title="App Settings"><MudIcon Icon="@Icons.Material.Filled.AdminPanelSettings" Size="Size.Small" /> Settings</a>
}
<MudIcon Icon="@(_expanded ? Icons.Material.Filled.ExpandMore : Icons.Material.Filled.ExpandLess)" Size="Size.Small" />
</div>
</MudStack>
@{
var ls = State.LockState;
var wfActive = ls?.Workflow is not null;
var grpActive = ls?.Groups is { } grpDict && grpDict.Values.Any(v => v is not null);
}
@if (_expanded)
{
@* ── Mode banner ── *@
@if (wfActive)
{
<div class="mode-banner mode-wf">
<MudIcon Icon="@Icons.Material.Filled.Bolt" Size="Size.Small" /> WF — @(ls!.Workflow!.Name)
<span class="mode-note">@Lang.T("Manual tắt", "Manual disabled")</span>
</div>
}
else if (grpActive)
{
<div class="mode-banner mode-manual">
<MudIcon Icon="@Icons.Material.Filled.Settings" Size="Size.Small" /> MANUAL
<span class="mode-note">@Lang.T("Workflow tắt", "Workflow disabled")</span>
</div>
}
else
{
<div class="mode-banner mode-free">@Lang.T("Không có ai nắm quyền", "No one holds control")</div>
}
@* ── OPERATIONS CONTROL row ── *@
<div class="ops-row @(grpActive && !IsManager ? "section-blocked" : "")">
<span class="ops-lbl">OPS</span>
@if (!CanWorkflow && UseReal)
{
<span class="mode-tag">Manual only</span>
}
@if (ls?.Workflow is { } wfHolder)
{
bool isMine = wfHolder.UserId == MyUserId;
<MudChip T="string" Size="Size.Small" Color="@(isMine ? Color.Success : Color.Error)"
Style="height:20px;font-size:10px;">
@(isMine ? Lang.T("Bạn giữ", "You hold") : wfHolder.Name)
</MudChip>
@if (isMine)
{
<MudButton Size="Size.Small" Variant="Variant.Outlined" Color="Color.Default"
Style="min-width:0;padding:1px 8px;" OnClick="ReleaseWorkflow">RELEASE</MudButton>
<MudIconButton Icon="@Icons.Material.Filled.Refresh" Size="Size.Small" Color="Color.Primary"
Style="padding:1px;" OnClick="RenewWorkflow" />
}
else if (IsManager)
{
<MudButton Size="Size.Small" Variant="Variant.Text" Color="Color.Error"
Style="min-width:0;padding:1px 6px;" OnClick="PreemptWorkflow">Preempt</MudButton>
}
else
{
var qPos = ls.WorkflowQueue?.ToList().FindIndex(w => w.UserId == MyUserId) ?? -1;
@if (qPos >= 0)
{
<MudText Typo="Typo.caption" Style="color:#9CA3AF;">@Lang.T("Chờ", "Queue") #@(qPos + 1)</MudText>
<MudIconButton Icon="@Icons.Material.Filled.Close" Size="Size.Small" Color="Color.Default"
Style="padding:1px;" OnClick="LeaveWorkflowQueue" />
}
else if (CanWorkflow)
{
<MudButton Size="Size.Small" Variant="Variant.Outlined" Color="Color.Warning"
Style="min-width:0;padding:1px 8px;" OnClick="JoinWorkflowQueue">JOIN</MudButton>
}
}
}
else if (!grpActive || IsManager)
{
<MudChip T="string" Size="Size.Small" Color="@(CanWorkflow ? Color.Success : Color.Default)"
Style="height:20px;font-size:10px;">Free</MudChip>
@if (CanWorkflow)
{
<MudButton Size="Size.Small" Variant="Variant.Filled" Color="Color.Success"
Style="min-width:0;padding:1px 10px;" OnClick="AcquireWorkflowControl">ACQUIRE</MudButton>
}
else
{
<span style="font-size:10px;color:#9CA3AF;font-style:italic;">@Lang.T("Cần quyền WF", "Need WF perm")</span>
}
}
else
{
<span class="ops-blocked-note">@Lang.T("Manual đang bật", "Manual is active")</span>
}
</div>
@if (ls?.WorkflowQueue is { Count: > 0 } wfQueue)
{
<div class="queue-list">
@foreach (var (w, i) in wfQueue.Select((w, i) => (w, i)))
{
<span class="queue-item @(w.IsPriority ? "q-priority" : "")">@(i + 1). @w.Name</span>
}
</div>
}
@* ── Group row ── *@
<div class="grp-row @(wfActive ? "section-blocked" : "")">
@foreach (var group in new[] { "ImrDobot", "AmrC1", "C2Asrs" })
{
var groupLabel = group switch { "ImrDobot" => "IMR·Dobot", "AmrC1" => "AMR·C1", _ => "C2·ASRS" };
LockHolderDto? groupHolder = null;
IReadOnlyList<WaiterDto>? groupQueue = null;
ls?.Groups?.TryGetValue(group, out groupHolder);
ls?.GroupQueues?.TryGetValue(group, out groupQueue);
<div class="grp-col">
<span class="grp-name">@groupLabel</span>
<div class="grp-actions">
@if (wfActive)
{
<span class="grp-wf-note">WF</span>
}
else if (groupHolder is not null)
{
bool isMine = groupHolder.UserId == MyUserId;
<MudChip T="string" Size="Size.Small" Color="@(isMine ? Color.Success : Color.Error)"
Style="height:18px;font-size:10px;margin:0;">
@(isMine ? Lang.T("Bạn", "You") : groupHolder.Name)
</MudChip>
@if (isMine)
{
var grp = group;
<MudButton Size="Size.Small" Variant="Variant.Outlined" Color="Color.Default"
Style="min-width:0;padding:1px 6px;" OnClick="() => ReleaseGroup(grp)">UNLOCK</MudButton>
}
else if (IsManager)
{
var grp = group;
<MudButton Size="Size.Small" Variant="Variant.Text" Color="Color.Error"
Style="min-width:0;padding:1px 4px;" OnClick="() => PreemptGroup(grp)">Unassign</MudButton>
}
else
{
var grp = group;
var qPos2 = groupQueue?.ToList().FindIndex(w => w.UserId == MyUserId) ?? -1;
@if (qPos2 >= 0)
{
<span style="font-size:10px;color:#9CA3AF;">#@(qPos2 + 1)</span>
<MudIconButton Icon="@Icons.Material.Filled.Close" Size="Size.Small" Color="Color.Default"
Style="padding:1px;" OnClick="() => LeaveGroupQueue(grp)" />
}
else if (CanManual)
{
<MudButton Size="Size.Small" Variant="Variant.Text" Color="Color.Warning"
Style="min-width:0;padding:1px 6px;" OnClick="() => JoinGroupQueue(grp)">JOIN</MudButton>
}
}
}
else
{
<MudChip T="string" Size="Size.Small"
Color="@(CanManual || IsManager ? Color.Success : Color.Default)"
Style="height:18px;font-size:10px;margin:0;">Free</MudChip>
var grp = group;
var assignedIds = State.LockState?.Groups?
.Where(kv => kv.Key != grp && kv.Value is not null)
.Select(kv => kv.Value!.UserId)
.ToHashSet() ?? new HashSet<string>();
var availableUsers = _users.Where(u => !assignedIds.Contains(u.Id)).ToList();
if (IsManager)
{
<MudMenu Icon="@Icons.Material.Filled.PersonAdd" Size="Size.Small"
Style="min-width:0;" IconColor="Color.Success"
>
@if (availableUsers.Count == 0)
{
<MudMenuItem Disabled="true">
<span style="font-size:11px;color:#9CA3AF;font-style:italic;">
@Lang.T("Hết user", "All assigned")
</span>
</MudMenuItem>
}
else
{
@foreach (var u in availableUsers)
{
var uid = u.Id;
var uname = u.Username;
<MudMenuItem OnClick="() => AssignGroup(grp, uid, uname)">
<span style="font-size:12px;">@u.Username</span>
<span style="font-size:10px;color:#9CA3AF;margin-left:6px;">@u.Role</span>
</MudMenuItem>
}
}
</MudMenu>
}
else if (CanManual)
{
<MudButton Size="Size.Small" Variant="Variant.Outlined" Color="Color.Primary"
Style="min-width:0;padding:1px 6px;" OnClick="() => LockGroup(grp)">LOCK</MudButton>
}
else
{
<span style="font-size:10px;color:#9CA3AF;font-style:italic;">@Lang.T("Cần Manual", "Need Manual")</span>
}
}
</div>
@if (groupQueue is { Count: > 0 })
{
<div class="grp-queue">
@foreach (var (w, i) in groupQueue.Select((w, i) => (w, i)))
{
<span class="queue-item @(w.IsPriority ? "q-priority" : "")">@(i + 1). @w.Name</span>
}
</div>
}
</div>
}
</div>
}
</MudPaper>
@code {
[Parameter] public bool UseReal { get; set; }
[Parameter] public string MyUserId { get; set; } = "";
[Parameter] public string MyRole { get; set; } = "";
[Parameter] public bool CanWorkflow { get; set; }
[Parameter] public bool CanManual { get; set; }
private bool IsManager => MyRole is "Manager" or "Admin";
private bool _expanded = true;
private bool _usersLoaded = false;
private List<UserItem> _users = new();
private void ToggleExpand() => _expanded = !_expanded;
protected override async Task OnInitializedAsync()
{
await State.StartAsync();
State.LockStateChanged += OnLockChanged;
State.SystemChanged += OnLockChanged;
Lang.LangChanged += OnLockChanged;
}
protected override async Task OnParametersSetAsync()
{
if (IsManager && !_usersLoaded)
{
_usersLoaded = true;
try
{
var list = await Http.GetFromJsonAsync<List<UserItem>>("/api/auth/users/active");
if (list is not null) _users = list;
}
catch (Exception ex)
{
Snackbar.Add($"Không tải được danh sách user: {ex.Message}", Severity.Warning);
}
}
}
record UserItem(string Id, string Username, string Role);
public ValueTask DisposeAsync()
{
State.LockStateChanged -= OnLockChanged;
State.SystemChanged -= OnLockChanged;
Lang.LangChanged -= OnLockChanged;
return ValueTask.CompletedTask;
}
private void OnLockChanged() => InvokeAsync(StateHasChanged);
// ── Workflow actions ───────────────────────────────────────────────────────
private async Task AcquireWorkflowControl()
{
var resp = await Http.PostAsync("/api/lock/workflow/acquire", null);
if ((int)resp.StatusCode == 423)
Snackbar.Add(Lang.T("Workflow đang bị giữ bởi người khác.", "Workflow is held by another user."), Severity.Warning);
else if ((int)resp.StatusCode == 403)
Snackbar.Add(Lang.T("Bạn không có quyền Workflow Mode.", "You don't have Workflow Mode permission."), Severity.Error);
else if (!resp.IsSuccessStatusCode)
Snackbar.Add(Lang.T("Không thể lấy quyền điều khiển.", "Failed to acquire control."), Severity.Error);
}
private async Task ReleaseWorkflow()
{
await Http.PostAsync("/api/lock/workflow/release", null);
}
private async Task RenewWorkflow()
{
var resp = await Http.PostAsync("/api/lock/workflow/renew", null);
if (resp.IsSuccessStatusCode) Snackbar.Add(Lang.T("Đã gia hạn quyền điều khiển.", "Control renewed."), Severity.Success);
}
private async Task PreemptWorkflow()
{
await Http.SendAsync(new HttpRequestMessage(HttpMethod.Delete, "/api/lock/workflow"));
Snackbar.Add(Lang.T("Đã thu hồi Workflow lock.", "Workflow lock preempted."), Severity.Info);
}
private async Task JoinWorkflowQueue()
{
await Http.PostAsync("/api/lock/workflow/queue", null);
Snackbar.Add(Lang.T("Đã vào hàng chờ Operations Control.", "Joined Operations Control queue."), Severity.Info);
}
private async Task LeaveWorkflowQueue()
{
await Http.SendAsync(new HttpRequestMessage(HttpMethod.Delete, "/api/lock/workflow/queue"));
}
// ── Group actions ──────────────────────────────────────────────────────────
private async Task LockGroup(string group)
{
var resp = await Http.PostAsync($"/api/lock/{group}/acquire", null);
if ((int)resp.StatusCode == 423)
Snackbar.Add(Lang.T($"Nhóm {group} đang bị giữ bởi người khác.", $"Group {group} is held by another user."), Severity.Warning);
else if ((int)resp.StatusCode == 403)
Snackbar.Add(Lang.T("Bạn không có quyền Manual Mode.", "You don't have Manual Mode permission."), Severity.Error);
else if (!resp.IsSuccessStatusCode)
Snackbar.Add(Lang.T($"Không thể khóa nhóm {group}.", $"Failed to lock group {group}."), Severity.Error);
}
private async Task ReleaseGroup(string group)
{
await Http.PostAsync($"/api/lock/{group}/release", null);
}
private async Task PreemptGroup(string group)
{
await Http.SendAsync(new HttpRequestMessage(HttpMethod.Delete, $"/api/lock/{group}"));
Snackbar.Add(Lang.T($"Đã thu hồi lock nhóm {group}.", $"Group {group} unassigned."), Severity.Info);
}
private async Task AssignGroup(string group, string userId, string displayName)
{
var resp = await Http.PostAsJsonAsync($"/api/lock/{group}/assign", new { UserId = userId, DisplayName = displayName });
if (resp.IsSuccessStatusCode)
Snackbar.Add(Lang.T($"Đã phân nhóm {group} cho {displayName}.", $"Group {group} assigned to {displayName}."), Severity.Success);
else
Snackbar.Add(Lang.T("Không thể phân nhóm.", "Failed to assign group."), Severity.Error);
}
private async Task JoinGroupQueue(string group)
{
await Http.PostAsync($"/api/lock/{group}/queue", null);
Snackbar.Add(Lang.T($"Đã vào hàng chờ nhóm {group}.", $"Joined group {group} queue."), Severity.Info);
}
private async Task LeaveGroupQueue(string group)
{
await Http.SendAsync(new HttpRequestMessage(HttpMethod.Delete, $"/api/lock/{group}/queue"));
}
}
<style>
.ops-row { display:flex; align-items:center; gap:5px; flex-wrap:wrap; margin-top:4px; padding-top:4px; border-top:1px solid rgba(255,255,255,0.05); }
.ops-lbl { font-size:10px; font-weight:700; color:#9CA3AF; letter-spacing:0.5px; white-space:nowrap; }
.ops-blocked-note { font-size:10px; color:#9CA3AF; font-style:italic; margin-left:auto; }
.grp-row { display:grid; grid-template-columns:1fr 1fr 1fr; gap:6px; margin-top:4px; padding-top:5px; border-top:1px solid rgba(255,255,255,0.05); }
.grp-row.section-blocked { opacity:0.45; pointer-events:none; }
.grp-col { display:flex; flex-direction:column; gap:3px; padding:4px 6px; border:1px solid rgba(255,255,255,0.05); border-radius:5px; }
.grp-name { font-size:10px; font-weight:700; color:#9CA3AF; white-space:nowrap; }
.grp-actions { display:flex; align-items:center; gap:3px; flex-wrap:wrap; }
.grp-wf-note { font-size:10px; color:#9CA3AF; font-style:italic; }
.grp-queue { display:flex; flex-wrap:wrap; gap:3px; padding-bottom:2px; }
.queue-list { display:flex; flex-wrap:wrap; gap:4px; margin-top:2px; padding-left:4px; }
.queue-item { font-size:10px; color:#9CA3AF; background:rgba(255,255,255,0.04); padding:1px 5px; border-radius:3px; }
.queue-item.q-priority { color:#4a9eff; }
.mode-banner { font-size:10px; font-weight:700; padding:3px 8px; border-radius:4px; margin:4px 0 2px;
display:flex; align-items:center; gap:6px; }
.mode-banner.mode-wf { background:rgba(243,156,18,0.1); border:1px solid rgba(243,156,18,0.3); color:#f39c12; }
.mode-banner.mode-manual { background:rgba(74,158,255,0.08); border:1px solid rgba(74,158,255,0.25); color:#4a9eff; }
.mode-banner.mode-free { background:rgba(255,255,255,0.03); border:1px solid rgba(255,255,255,0.07); color:#9CA3AF; }
.mode-note { font-size:9px; font-weight:400; opacity:0.7; margin-left:auto; }
.mode-tag { font-size:9px; font-weight:700; padding:1px 5px; border-radius:3px;
background:rgba(74,158,255,0.1); border:1px solid rgba(74,158,255,0.2); color:#3a7bbf; }
</style>

View File

@@ -0,0 +1,330 @@
@rendermode @(new InteractiveWebAssemblyRenderMode(prerender: false))
@implements IAsyncDisposable
@using Lab505.Shared
@using Lab505.Client.Services
@inject StateService State
@inject IJSRuntime JS
<div class="mp-wrap" @ref="_el"
@onmousedown="OnMouseDown"
@onmousemove="OnMouseMove"
@onmouseup="OnMouseUp"
@onmouseleave="OnMouseLeave"
@ontouchstart="OnTouchStart"
@ontouchmove="OnTouchMove"
@ontouchend="OnTouchEnd"
style="cursor:@(_dragging?"grabbing":"grab")">
<svg width="100%" height="100%" xmlns="http://www.w3.org/2000/svg" style="display:block">
<defs>
<!-- 1 m minor grid -->
<pattern id="mp-g1"
width="@F(_s)" height="@F(_s)"
x="@F(Mod(_panX, _s))" y="@F(Mod(_panY, _s))"
patternUnits="userSpaceOnUse">
<path d="M @F(_s) 0 L 0 0 0 @F(_s)" fill="none" stroke="#232323" stroke-width="1"/>
</pattern>
<!-- 5 m major grid -->
<pattern id="mp-g5"
width="@F(5*_s)" height="@F(5*_s)"
x="@F(Mod(_panX, 5*_s))" y="@F(Mod(_panY, 5*_s))"
patternUnits="userSpaceOnUse">
<path d="M @F(5*_s) 0 L 0 0 0 @F(5*_s)" fill="none" stroke="#2c2c2c" stroke-width="1.5"/>
</pattern>
</defs>
<!-- Background + grid layers -->
<rect width="100%" height="100%" fill="#1a1a1a"/>
<rect width="100%" height="100%" fill="url(#mp-g1)"/>
<rect width="100%" height="100%" fill="url(#mp-g5)"/>
<!-- Axes -->
<line x1="@F(ToX(-100))" y1="@F(ToY(0))" x2="@F(ToX(100))" y2="@F(ToY(0))"
stroke="#2e2e2e" stroke-width="1.5"/>
<line x1="@F(ToX(0))" y1="@F(ToY(-100))" x2="@F(ToX(0))" y2="@F(ToY(100))"
stroke="#2e2e2e" stroke-width="1.5"/>
<!-- Grid coordinate labels (X axis, every 5 m) -->
@for (int gx = -15; gx <= 15; gx += 5)
{
double lx = ToX(gx), ly = ToY(0) + 14;
if (lx > 10 && lx < 3000)
{
@SvgTxt(lx, ly, "#383838", 10, "middle", "", gx.ToString())
}
}
<!-- Grid coordinate labels (Y axis, every 5 m) -->
@for (int gy = -15; gy <= 15; gy += 5)
{
if (gy == 0) continue;
double lx = ToX(0) + 5, ly = ToY(gy);
if (ly > 10 && ly < 3000)
{
@SvgTxt(lx, ly, "#383838", 10, "start", "middle", gy.ToString())
}
}
<!-- IMR trail -->
@if (_imrTrail.Count > 1)
{
<polyline points="@TrailPts(_imrTrail)"
fill="none" stroke="#4a9eff" stroke-width="2.5"
stroke-opacity="0.35" stroke-linejoin="round" stroke-linecap="round"/>
}
<!-- AMR trail -->
@if (_amrTrail.Count > 1)
{
<polyline points="@TrailPts(_amrTrail)"
fill="none" stroke="#4caf50" stroke-width="2.5"
stroke-opacity="0.35" stroke-linejoin="round" stroke-linecap="round"/>
}
<!-- Waypoints -->
@foreach (var wp in _waypoints)
{
double wx = ToX(wp.X), wy = ToY(wp.Y);
<g style="pointer-events:none">
<line x1="@F(wx-6)" y1="@F(wy)" x2="@F(wx+6)" y2="@F(wy)"
stroke="@wp.Color" stroke-width="1.5" opacity="0.4"/>
<line x1="@F(wx)" y1="@F(wy-6)" x2="@F(wx)" y2="@F(wy+6)"
stroke="@wp.Color" stroke-width="1.5" opacity="0.4"/>
<circle cx="@F(wx)" cy="@F(wy)" r="4"
fill="none" stroke="@wp.Color" stroke-width="1.5" opacity="0.5"/>
@SvgTxtColor(wx, wy - 11, wp.Color, 11, "middle", "", wp.Name, "opacity:0.6;user-select:none")
</g>
}
<!-- IMR robot -->
@{
double ix = ToX(State.Imr.X), iy = ToY(State.Imr.Y);
bool io = State.Imr.IsOnline;
string ic = io ? "#4a9eff" : "#333";
}
<g style="pointer-events:none">
@if (io) { <circle cx="@F(ix)" cy="@F(iy)" r="20" fill="#4a9eff" fill-opacity="0.07"/> }
<circle cx="@F(ix)" cy="@F(iy)" r="9" fill="@ic" stroke="#111" stroke-width="2"/>
<polygon points="@F(ix),@F(iy-15) @F(ix-4),@F(iy-9) @F(ix+4),@F(iy-9)"
fill="@ic" opacity="0.7"/>
<text x="@F(ix)" y="@F(iy - 20)" fill="@ic"
font-size="11" font-weight="600" text-anchor="middle"
style="user-select:none">IMR</text>
<text x="@F(ix)" y="@F(iy + 26)" fill="#505050"
font-size="9" text-anchor="middle"
style="user-select:none">(@State.Imr.X.ToString("F2", CI),@State.Imr.Y.ToString("F2", CI))</text>
</g>
<!-- AMR robot -->
@{
double ax = ToX(State.Amr.X), ay = ToY(State.Amr.Y);
bool ao = State.Amr.IsOnline;
string ac = ao ? "#4caf50" : "#333";
}
<g style="pointer-events:none">
@if (ao) { <circle cx="@F(ax)" cy="@F(ay)" r="20" fill="#4caf50" fill-opacity="0.07"/> }
<circle cx="@F(ax)" cy="@F(ay)" r="9" fill="@ac" stroke="#111" stroke-width="2"/>
<polygon points="@F(ax),@F(ay-15) @F(ax-4),@F(ay-9) @F(ax+4),@F(ay-9)"
fill="@ac" opacity="0.7"/>
<text x="@F(ax)" y="@F(ay - 20)" fill="@ac"
font-size="11" font-weight="600" text-anchor="middle"
style="user-select:none">AMR</text>
<text x="@F(ax)" y="@F(ay + 26)" fill="#505050"
font-size="9" text-anchor="middle"
style="user-select:none">(@State.Amr.X.ToString("F2", CI),@State.Amr.Y.ToString("F2", CI))</text>
</g>
<!-- Legend (top-left) -->
<g transform="translate(10,10)" style="pointer-events:none">
<rect width="116" height="68" rx="5"
fill="rgba(0,0,0,0.72)" stroke="#2a2a2a" stroke-width="1"/>
<circle cx="14" cy="19" r="5" fill="@(io ? "#4a9eff" : "#333")"/>
<text x="24" y="23" fill="#aaa" font-size="11">IMR @(State.Imr.IsOnline ? "●" : "○")</text>
<circle cx="14" cy="39" r="5" fill="@(ao ? "#4caf50" : "#333")"/>
<text x="24" y="43" fill="#aaa" font-size="11">AMR @(State.Amr.IsOnline ? "●" : "○")</text>
<text x="8" y="59" fill="#3a3a3a" font-size="9">1 ô = 1 m²</text>
</g>
</svg>
<div class="mp-zoom-badge">×@_zoom.ToString("F1", CI)</div>
<button class="mp-reset" @onclick="ResetView" title="Reset view">⊙</button>
</div>
@code {
ElementReference _el;
DotNetObjectReference<MapPanel>? _self;
// ── Pan / Zoom ────────────────────────────────────────────────
double _panX = 150, _panY = 180;
double _zoom = 1.0;
const double CELL = 40.0;
double _s => _zoom * CELL;
// ── Drag ─────────────────────────────────────────────────────
bool _dragging;
double _dragCX, _dragCY, _dragPX, _dragPY;
// ── Trail ─────────────────────────────────────────────────────
const int MAX_TRAIL = 200;
readonly Queue<(double X, double Y)> _imrTrail = new();
readonly Queue<(double X, double Y)> _amrTrail = new();
// ── Waypoints ─────────────────────────────────────────────────
record Wp(string Name, double X, double Y, string Color);
static readonly Wp[] _waypoints =
[
new("C1", RobotPositions.IMR_C1_X, RobotPositions.IMR_C1_Y, "#5b9bd5"),
new("ABB", RobotPositions.IMR_ABB_X, RobotPositions.IMR_ABB_Y, "#5b9bd5"),
new("Cap1", RobotPositions.AMR_CAP1_X, RobotPositions.AMR_CAP1_Y, "#5cb85c"),
new("Cap2", RobotPositions.AMR_CAP2_X, RobotPositions.AMR_CAP2_Y, "#5cb85c"),
new("Home", RobotPositions.AMR_HOME_X, RobotPositions.AMR_HOME_Y, "#888"),
];
static readonly System.Globalization.CultureInfo CI =
System.Globalization.CultureInfo.InvariantCulture;
// ── Lifecycle ─────────────────────────────────────────────────
protected override void OnInitialized()
{
State.ImrChanged += OnImrChanged;
State.AmrChanged += OnAmrChanged;
}
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (!firstRender) return;
_self = DotNetObjectReference.Create(this);
await JS.InvokeVoidAsync("eval",
"if(!window._mpWheelInit)window._mpWheelInit=function(el,dn){" +
"el.addEventListener('wheel',function(e){e.preventDefault();" +
"var r=el.getBoundingClientRect();" +
"dn.invokeMethodAsync('OnWheelJs',e.deltaY,e.clientX-r.left,e.clientY-r.top);" +
"},{passive:false});};");
await JS.InvokeVoidAsync("_mpWheelInit", _el, _self);
}
[JSInvokable]
public void OnWheelJs(double deltaY, double offsetX, double offsetY)
{
double factor = deltaY < 0 ? 1.15 : 1.0 / 1.15;
double newZoom = Math.Clamp(_zoom * factor, 0.12, 12.0);
double f = newZoom / _zoom;
_panX = offsetX + (_panX - offsetX) * f;
_panY = offsetY + (_panY - offsetY) * f;
_zoom = newZoom;
InvokeAsync(StateHasChanged);
}
void ResetView() { _panX = 150; _panY = 180; _zoom = 1.0; }
// ── Mouse pan ─────────────────────────────────────────────────
void OnMouseDown(MouseEventArgs e)
{
if (e.Button != 0) return;
_dragging = true;
_dragCX = e.ClientX; _dragCY = e.ClientY;
_dragPX = _panX; _dragPY = _panY;
}
void OnMouseMove(MouseEventArgs e)
{
if (!_dragging) return;
_panX = _dragPX + (e.ClientX - _dragCX);
_panY = _dragPY + (e.ClientY - _dragCY);
}
void OnMouseUp(MouseEventArgs e) { if (e.Button == 0) _dragging = false; }
void OnMouseLeave(MouseEventArgs e) { _dragging = false; }
// ── Touch pan ─────────────────────────────────────────────────
void OnTouchStart(TouchEventArgs e)
{
if (e.Touches.Length != 1) return;
var t = e.Touches[0]; _dragging = true;
_dragCX = t.ClientX; _dragCY = t.ClientY;
_dragPX = _panX; _dragPY = _panY;
}
void OnTouchMove(TouchEventArgs e)
{
if (!_dragging || e.Touches.Length != 1) return;
var t = e.Touches[0];
_panX = _dragPX + (t.ClientX - _dragCX);
_panY = _dragPY + (t.ClientY - _dragCY);
}
void OnTouchEnd(TouchEventArgs e) { _dragging = false; }
// ── State updates ─────────────────────────────────────────────
void OnImrChanged() { AddTrail(_imrTrail, State.Imr.X, State.Imr.Y); InvokeAsync(StateHasChanged); }
void OnAmrChanged() { AddTrail(_amrTrail, State.Amr.X, State.Amr.Y); InvokeAsync(StateHasChanged); }
static void AddTrail(Queue<(double, double)> q, double x, double y)
{
if (q.TryPeek(out var last)
&& Math.Abs(last.Item1 - x) < 0.005
&& Math.Abs(last.Item2 - y) < 0.005) return;
q.Enqueue((x, y));
while (q.Count > MAX_TRAIL) q.Dequeue();
}
// ── Coordinate helpers ────────────────────────────────────────
double ToX(double wx) => _panX + wx * _s;
double ToY(double wy) => _panY - wy * _s; // flip Y: VDA5050 Y-up → SVG Y-down
static double Mod(double a, double b) => ((a % b) + b) % b;
static string F(double v) => v.ToString("F2", CI);
string TrailPts(Queue<(double X, double Y)> q)
=> string.Join(" ", q.Select(p => $"{F(ToX(p.X))},{F(ToY(p.Y))}"));
// ── SVG <text> helpers (avoid Razor parser conflict inside code blocks) ──
// Blazor treats <text> as a Razor directive inside @for/@foreach — use MarkupString instead.
static MarkupString SvgTxt(double x, double y, string fill, int size,
string anchor, string baseline, string content)
{
var bl = baseline.Length > 0 ? $" dominant-baseline=\"{baseline}\"" : "";
return (MarkupString)(
$"<text x=\"{x:F2}\" y=\"{y:F2}\" fill=\"{fill}\" font-size=\"{size}\"" +
$" text-anchor=\"{anchor}\"{bl}" +
$" style=\"pointer-events:none;user-select:none\">{content}</text>");
}
static MarkupString SvgTxtColor(double x, double y, string fill, int size,
string anchor, string baseline, string content, string style)
{
var bl = baseline.Length > 0 ? $" dominant-baseline=\"{baseline}\"" : "";
return (MarkupString)(
$"<text x=\"{x:F2}\" y=\"{y:F2}\" fill=\"{fill}\" font-size=\"{size}\"" +
$" text-anchor=\"{anchor}\"{bl}" +
$" style=\"{style}\">{content}</text>");
}
public ValueTask DisposeAsync()
{
State.ImrChanged -= OnImrChanged;
State.AmrChanged -= OnAmrChanged;
_self?.Dispose();
return ValueTask.CompletedTask;
}
}
<style>
.mp-wrap {
width: 100%; height: 100%;
position: relative;
overflow: hidden;
background: #1a1a1a;
touch-action: none;
user-select: none;
-webkit-user-select: none;
}
.mp-zoom-badge {
position: absolute; bottom: 12px; left: 12px;
color: #383838; font-size: 10px;
font-family: monospace; pointer-events: none;
}
.mp-reset {
position: absolute; bottom: 10px; right: 10px;
width: 28px; height: 28px;
background: rgba(0,0,0,0.65); border: 1px solid #2e2e2e;
border-radius: 5px; color: #555; font-size: 15px;
cursor: pointer; padding: 0; line-height: 1;
transition: color .15s, border-color .15s;
}
.mp-reset:hover { color: #aaa; border-color: #555; }
</style>

View File

@@ -0,0 +1,41 @@
@implements IAsyncDisposable
@inject StateService State
@inject ISnackbar Snackbar
@inject ScriptLogService ScriptLog
@* Component không render gì — lắng nghe notification, ghi vào output log + Snackbar *@
@code {
[Parameter] public bool Muted { get; set; }
protected override async Task OnInitializedAsync()
{
await State.StartAsync();
State.NotificationReceived += OnNotification;
}
private void OnNotification(NotificationDto n)
{
ScriptLog.LogNotification(n);
// Snackbar toast — chỉ khi chưa tắt
if (!Muted)
{
var severity = n.Level switch
{
"success" => Severity.Success,
"error" => Severity.Error,
"warning" => Severity.Warning,
"heartbeat" => Severity.Normal,
_ => Severity.Info,
};
Snackbar.Add(n.Message, severity);
}
}
public ValueTask DisposeAsync()
{
State.NotificationReceived -= OnNotification;
return ValueTask.CompletedTask;
}
}

View File

@@ -0,0 +1,920 @@
@rendermode @(new InteractiveWebAssemblyRenderMode(prerender: false))
@implements IAsyncDisposable
@using Microsoft.AspNetCore.SignalR.Client
@inject StateService State
@inject LangService Lang
@inject ScriptLogService ScriptLog
<MudMessageBox @ref="_confirmRunBox" Title="@Lang.T("Xác nhận chạy script (REAL)", "Confirm run script (REAL)")" CancelText="@Lang.T("Hủy", "Cancel")">
<MessageContent>
@if (_loadedName != null)
{
<MudText Typo="Typo.caption" Style="color:#4a9eff;margin-bottom:6px;"><MudIcon Icon="@Icons.Material.Filled.FiberManualRecord" Size="Size.Small" /> @_loadedName</MudText>
}
<MudText Typo="Typo.caption" Style="color:#aaa;margin-bottom:4px;">@Lang.T("Code sẽ được thực thi:", "Code to be executed:")</MudText>
<pre style="max-height:300px;overflow-y:auto;background:#27292b;color:#cfc;font-size:11px;
padding:8px;border-radius:4px;border:1px solid #333;margin:0;white-space:pre-wrap;
word-wrap:break-word;">@_pendingCode</pre>
</MessageContent>
<YesButton>
<MudButton Color="Color.Primary" Variant="Variant.Filled" StartIcon="@Icons.Material.Filled.PlayArrow">@Lang.T("Chạy", "Run")</MudButton>
</YesButton>
</MudMessageBox>
<div class="script-root">
<div class="script-toolbar">
<MudText Typo="Typo.subtitle2" Style="color:#ddd;">SCRIPT</MudText>
<MudButton Variant="Variant.Filled" Color="Color.Primary" Size="Size.Small"
StartIcon="@Icons.Material.Filled.PlayArrow"
OnClick="RunScript" Disabled="@(_isRunning || IsLockBlocked)">Run</MudButton>
<MudButton Variant="Variant.Filled" Color="Color.Error" Size="Size.Small"
StartIcon="@Icons.Material.Filled.Stop"
OnClick="StopScript" Disabled="!_isRunning">@Lang.T("Hủy", "Cancel")</MudButton>
@if (IsLockBlocked)
{
<MudChip T="string" Icon="@Icons.Material.Filled.Warning" Color="Color.Warning"
Variant="Variant.Outlined" Size="Size.Small"
Style="height:24px;font-size:10px;margin:0;">@Lang.T("Cần giữ lock để chạy script", "Lock required to run script")</MudChip>
}
else if (IsWorkflowMode)
{
<MudChip T="string" Icon="@Icons.Material.Filled.Bolt" Color="Color.Warning"
Variant="Variant.Outlined" Size="Size.Small"
Style="height:24px;font-size:10px;margin:0;opacity:0.8;">Workflow</MudChip>
}
else if (IsManualMode)
{
<MudChip T="string" Icon="@Icons.Material.Filled.Settings" Color="Color.Info"
Variant="Variant.Outlined" Size="Size.Small"
Style="height:24px;font-size:10px;margin:0;opacity:0.8;">Manual</MudChip>
}
@if (_hubOk)
{
<MudChip T="string" Icon="@Icons.Material.Filled.CheckCircle" Color="Color.Success"
Variant="Variant.Text" Size="Size.Small"
Style="height:24px;font-size:11px;margin:0;">Connected</MudChip>
}
else
{
<MudButton Variant="Variant.Text" Color="Color.Error" Size="Size.Small"
OnClick="ConnectHub"
Style="font-size:11px;padding:0 4px;min-height:auto;min-width:auto;text-decoration:underline dotted;">Disconnect</MudButton>
}
<div style="margin-left:auto;display:flex;align-items:center;gap:4px;">
@if (_saveOpen)
{
<MudTextField @bind-Value="_saveName" Immediate="true"
Placeholder="@Lang.T("Tên script...", "Script name...")" OnKeyDown="SaveKeyDown" AutoFocus="true"
Variant="Variant.Outlined" Margin="Margin.Dense"
Style="width:140px;" />
<MudIconButton Icon="@Icons.Material.Filled.Check" Size="Size.Small"
Style="color:#2ecc71;padding:4px;" OnClick="DoSave" />
<MudIconButton Icon="@Icons.Material.Filled.Close" Size="Size.Small"
Style="color:#e74c3c;padding:4px;" OnClick="() => _saveOpen = false" />
}
else
{
@if (_loadedName != null)
{
<MudChip T="string" Icon="@Icons.Material.Filled.FiberManualRecord"
Color="Color.Info" Variant="Variant.Text" Size="Size.Small"
Style="max-width:160px;height:24px;font-size:11px;margin:0;"
title="@_loadedName">@_loadedName</MudChip>
}
<MudButton Variant="Variant.Text" Size="Size.Small" OnClick="OpenSave"
Style="color:#aaa;padding:0 6px;min-width:0;font-size:11px;">
@Lang.T("Lưu", "Save")
</MudButton>
}
<MudButton Variant="Variant.Outlined" Size="Size.Small"
Style="min-width:40px;color:#aaa;border-color:#555;padding:0 8px;"
OnClick="ToggleLang">@Lang.Current.ToUpper()</MudButton>
</div>
</div>
<div class="script-body">
<!-- ── File sidebar ─────────────────────────────────────── -->
<div id="fileSidebar" class="file-sidebar @(_sidebarOpen ? "" : "collapsed")">
<div class="sidebar-header">
<span>FILES</span>
<MudButton Variant="Variant.Text" Size="Size.Small" OnClick="NewScript"
Style="color:#888;padding:0 4px;min-width:0;height:22px;font-size:12px;border:1px solid #444;border-radius:3px;">+</MudButton>
</div>
<div class="sidebar-list">
@if (_scripts.Count == 0)
{
<div class="sidebar-empty">@Lang.T("Chưa có script", "No scripts")</div>
}
else
{
@foreach (var s in _scripts)
{
var item = s;
var isActive = _loadedId == item.Id;
<div class="@("sidebar-item" + (isActive ? " active" : ""))"
@onclick="() => LoadScript(item)">
<div class="sidebar-item-name" title="@item.Name">@item.Name</div>
<div class="sidebar-item-meta">@item.UpdatedDisplay</div>
<span class="sidebar-del-wrap" @onclick:stopPropagation="true">
<MudIconButton Class="sidebar-del-btn" Icon="@Icons.Material.Filled.Close"
Size="Size.Small"
OnClick="() => DeleteScript(item.Id)" />
</span>
</div>
}
}
</div>
</div>
<!-- ── Toggle / drag strip ──────────────────────────────── -->
<MudIconButton id="sidebarToggle" Class="sidebar-toggle"
Icon="@(_sidebarOpen ? Icons.Material.Filled.ChevronLeft : Icons.Material.Filled.ChevronRight)"
Size="Size.Small"
OnClick="ToggleSidebar"
Style="width:14px;padding:0;min-width:0;border-radius:0;height:100%;"
title="Kéo để thay đổi kích thước · Click để thu/mở" />
<!-- ── Editor + output column ───────────────────────────── -->
<div class="editor-column">
<div id="scriptEditor" class="monaco-editor-host"></div>
<div id="outputResizeHandle" class="output-resize-handle"></div>
<div id="outputPane" class="output-pane">
@* ── Output / History tabs ── *@
<div class="output-tabs">
<MudButton Variant="Variant.Text" Size="Size.Small"
Class="@("tab-btn" + (!_historyTab ? " tab-on" : ""))"
OnClick="() => SetTab(false)">Output</MudButton>
@if (_isManager)
{
<MudButton Variant="Variant.Text" Size="Size.Small"
Class="@("tab-btn" + (_historyTab ? " tab-on" : ""))"
OnClick="() => SetTab(true)">
@Lang.T("Lịch sử", "History")
@if (_historyLoading) { <MudProgressCircular Size="Size.Small" Indeterminate="true" Style="width:10px;height:10px;margin-left:4px;" /> }
</MudButton>
}
@{
var activeFilters = _historyTab ? _histFilters : _logFilters;
}
<div class="lf-bar">
@foreach (var lvl in _logLevels)
{
var badge = lvl.Badge;
var color = lvl.Color;
var isOn = activeFilters.Contains(badge);
<MudButton Size="Size.Small" Variant="Variant.Outlined"
Style="@($"min-width:0;padding:0 7px;height:22px;font-size:10px;font-family:Consolas,monospace;font-weight:700;letter-spacing:0.3px;flex-shrink:0;{(isOn ? $"color:{color};border-color:{color};background:rgba(255,255,255,0.05);" : "color:#555;border-color:#2a2a2a;")}")"
OnClick="@(() => { if (!activeFilters.Add(badge)) activeFilters.Remove(badge); })">@badge</MudButton>
}
@if (!_historyTab)
{
<MudTextField @bind-Value="_logSearch" Immediate="true"
Placeholder="search log..."
Variant="Variant.Outlined" Margin="Margin.Dense"
Class="lf-field" Style="flex:1;min-width:60px;" />
}
else
{
<MudTextField @bind-Value="_histSearch" Immediate="true"
Placeholder="search log..."
Variant="Variant.Outlined" Margin="Margin.Dense"
Class="lf-field" Style="flex:1;min-width:60px;" />
@if (_isManager)
{
<MudTextField @bind-Value="_searchUsername" Immediate="true"
Placeholder="search user..."
Variant="Variant.Outlined" Margin="Margin.Dense"
Class="lf-field" Style="width:110px;flex-shrink:0;"
OnKeyDown="SearchKeyDown" />
}
}
</div>
<MudTooltip Text="@Lang.T("Xóa", "Clear")" Placement="Placement.Left">
<MudIconButton Icon="@Icons.Material.Filled.DeleteSweep" Size="Size.Small"
OnClick="ClearActive"
Style="color:#3a3a3a;padding:0 8px;flex-shrink:0;" />
</MudTooltip>
</div>
@if (!_historyTab)
{
<div class="output-area" @ref="_outputPanel">
@foreach (var line in FilteredLines)
{
<div class="log-line">@((MarkupString)line)</div>
}
</div>
}
else
{
<div class="output-area history-area">
@if (_historyLoading)
{
<div style="display:flex;align-items:center;gap:8px;padding:12px;">
<MudProgressCircular Size="Size.Small" Indeterminate="true" Color="Color.Default" />
<MudText Typo="Typo.caption" Style="color:#444;">@Lang.T("Đang tải...", "Loading...")</MudText>
</div>
}
else if (_historyLogs.Count == 0)
{
<div style="padding:16px;text-align:center;">
<MudIcon Icon="@Icons.Material.Filled.Inbox" Style="color:#2a2a2a;font-size:32px;" />
<MudText Typo="Typo.caption" Style="color:#444;display:block;margin-top:4px;">@Lang.T("Chưa có lịch sử.", "No history yet.")</MudText>
</div>
}
else
{
@foreach (var log in FilteredHistory)
{
<div class="history-row">
<span class="hist-time">@log.StartedAt</span>
@if (_isManager)
{
<span class="hist-user">@log.Username</span>
}
<span class="hist-name" title="@log.ScriptName">
@(string.IsNullOrEmpty(log.ScriptName) ? "(anonymous)" : log.ScriptName)
</span>
<MudChip T="string" Color="@StatusColor(log.Status)" Size="Size.Small"
Variant="Variant.Text" Class="hist-chip">@log.Status</MudChip>
@if (!string.IsNullOrEmpty(log.Error))
{
<MudTooltip Text="@log.Error" Placement="Placement.Left">
<MudIcon Icon="@Icons.Material.Filled.ErrorOutline"
Size="Size.Small" Color="Color.Error" Style="font-size:14px;" />
</MudTooltip>
}
</div>
}
}
</div>
}
</div> @* end outputPane *@
</div>
</div>
</div>
@code {
[Inject] HttpClient Http { get; set; } = default!;
[Inject] IJSRuntime JS { get; set; } = default!;
// ── Output filter ─────────────────────────────────────────────────────────
private ElementReference _outputPanel;
private readonly HashSet<string> _logFilters = new();
private readonly HashSet<string> _histFilters = new();
private string _logSearch = "";
private string _histSearch = "";
private static readonly (string Badge, string Color)[] _logLevels =
[
("INFO", "#42a5f5"), ("DONE", "#66bb6a"), ("WARN", "#ffa726"),
("ERR", "#ef5350"), ("DEV", "#9575cd")
];
private IEnumerable<string> FilteredLines
{
get
{
var lines = (IEnumerable<string>)ScriptLog.Lines;
if (_logFilters.Count > 0)
lines = lines.Where(l => _logFilters.Any(f => l.Contains($">{f}<")));
if (!string.IsNullOrEmpty(_logSearch))
lines = lines.Where(l => l.Contains(_logSearch, StringComparison.OrdinalIgnoreCase));
return lines;
}
}
private static string StatusToLevel(string s) => s switch
{
"Success" => "DONE",
"Cancelled" => "WARN",
"Running" => "INFO",
_ => "ERR"
};
private IEnumerable<LogItem> FilteredHistory
{
get
{
var items = (IEnumerable<LogItem>)_historyLogs;
if (_histFilters.Count > 0)
items = items.Where(l => _histFilters.Contains(StatusToLevel(l.Status)));
if (!string.IsNullOrEmpty(_histSearch))
items = items.Where(l =>
(l.ScriptName ?? "").Contains(_histSearch, StringComparison.OrdinalIgnoreCase) ||
l.StartedAt.Contains(_histSearch, StringComparison.OrdinalIgnoreCase));
if (!string.IsNullOrEmpty(_searchUsername))
items = items.Where(l =>
(l.Username ?? "").Contains(_searchUsername, StringComparison.OrdinalIgnoreCase));
return items;
}
}
private void ClearActive()
{
if (_historyTab) _historyLogs.Clear();
else ScriptLog.Clear();
}
private Color StatusColor(string s) => s switch
{
"Success" => Color.Success,
"Cancelled" => Color.Warning,
"Running" => Color.Info,
_ => Color.Error
};
private bool _isRunning;
private bool _hubOk;
private CancellationTokenSource? _cts;
private HubConnection? _hub;
// ── History ───────────────────────────────────────────────────────────────
private bool _isManager;
private bool _historyTab;
private bool _historyLoading;
private string _searchUsername = "";
private List<LogItem> _historyLogs = [];
record LogItem(string StartedAt, string Username, string ScriptName, string Status, string? Error);
private async Task SetTab(bool history)
{
_historyTab = history;
if (history && _historyLogs.Count == 0) await LoadHistory();
}
private async Task SearchKeyDown(KeyboardEventArgs e)
{
if (e.Key == "Enter") await LoadHistory();
}
private async Task LoadHistory()
{
_historyLoading = true;
StateHasChanged();
try
{
string url = _isManager
? $"/api/script/logs{(string.IsNullOrWhiteSpace(_searchUsername) ? "" : $"?username={Uri.EscapeDataString(_searchUsername)}")}"
: "/api/script/logs/me";
var list = await Http.GetFromJsonAsync<List<LogItem>>(url);
_historyLogs = list ?? [];
}
catch { }
_historyLoading = false;
StateHasChanged();
}
// ── Lock awareness ────────────────────────────────────────────────────────
private string _myUserId = "";
/// Script chạy trên real hardware → phải giữ workflow lock hoặc ít nhất 1 group lock
private bool IsLockBlocked
{
get
{
if (State.System.IsSimulation) return false; // sim: không cần lock
var ls = State.LockState;
if (ls is null) return false; // real nhưng chưa có snapshot
bool hasWorkflow = ls.Workflow?.UserId == _myUserId;
bool hasGroup = ls.Groups?.Values.Any(h => h?.UserId == _myUserId) == true;
return !hasWorkflow && !hasGroup;
}
}
private bool IsWorkflowMode =>
!State.System.IsSimulation && State.LockState?.Workflow?.UserId == _myUserId;
private bool IsManualMode =>
!State.System.IsSimulation && !IsWorkflowMode
&& (State.LockState?.Groups?.Values.Any(h => h?.UserId == _myUserId) == true);
// ── Script storage ────────────────────────────────────────────────────────
private List<ScriptItem> _scripts = [];
private int? _loadedId;
private string? _loadedName;
private bool _saveOpen;
private string _saveName = "";
private bool _sidebarOpen = true;
MudMessageBox? _confirmRunBox;
private string _pendingCode = "";
record ScriptItem(int Id, string Name, string UpdatedDisplay);
protected override async Task OnInitializedAsync()
{
await State.StartAsync();
State.LockStateChanged += OnStateChanged;
State.SystemChanged += OnStateChanged;
Lang.LangChanged += OnLangChanged;
ScriptLog.LogChanged += OnLogChanged;
await ConnectHub();
await RefreshScriptList();
try
{
var me = await Http.GetFromJsonAsync<MeDto>("/api/auth/me");
_myUserId = me?.UserId ?? "";
_isManager = me?.Role is "Manager" or "Admin";
ScriptLog.IsDevMode = me?.Role is "Admin";
}
catch { }
}
private void OnStateChanged() => InvokeAsync(StateHasChanged);
private void OnLogChanged() => InvokeAsync(async () =>
{
StateHasChanged();
try { await JS.InvokeVoidAsync("eval",
"var el=document.querySelector('.output-area');if(el)el.scrollTop=0;"); }
catch { }
});
private void OnLangChanged() => _ = InvokeAsync(async () =>
{
try { await JS.InvokeVoidAsync("setEditorLang", Lang.Current); } catch { }
StateHasChanged();
});
protected override async Task OnAfterRenderAsync(bool firstRender)
{
if (firstRender)
{
await JS.InvokeVoidAsync("initScriptEditor");
await JS.InvokeVoidAsync("splitter.initSidebarSplit");
await JS.InvokeVoidAsync("splitter.initOutputSplit");
}
}
private async Task ToggleSidebar()
{
// Skip toggle if the mousedown was actually a drag
bool wasDrag = false;
try { wasDrag = await JS.InvokeAsync<bool>("(function(){ var h=document.getElementById('sidebarToggle'); return h && h._wasDragged ? h._wasDragged() : false; })"); }
catch { }
if (wasDrag) return;
_sidebarOpen = !_sidebarOpen;
var w = _sidebarOpen ? "180px" : "0px";
try { await JS.InvokeVoidAsync("eval", $"var s=document.getElementById('fileSidebar');if(s)s.style.width='{w}';"); }
catch { }
}
// ── Hub connections ───────────────────────────────────────────────────────
private async Task ConnectHub()
{
try
{
if (_hub != null)
{
await _hub.DisposeAsync();
_hub = null;
}
_hub = new HubConnectionBuilder()
.WithUrl(new Uri(Http.BaseAddress!, "/scriptHub"))
.WithAutomaticReconnect()
.Build();
_hub.On<string>("scriptLog", line =>
{
ScriptLog.Log(line); // fires LogChanged → OnLogChanged → StateHasChanged
});
_hub.Reconnected += async _ => { _hubOk = true; await InvokeAsync(StateHasChanged); };
_hub.Closed += async _ => { _hubOk = false; await InvokeAsync(StateHasChanged); };
await _hub.StartAsync();
_hubOk = true;
await InvokeAsync(StateHasChanged);
}
catch (Exception ex)
{
ScriptLog.Log($"❌ Hub: {ex.Message}");
}
}
// ── Run / Stop ────────────────────────────────────────────────────────────
private async Task RunScript()
{
if (!_hubOk) { ScriptLog.Log(Lang.T("❌ Hub chưa kết nối.", "❌ Hub not connected.")); return; }
string code;
try { code = await JS.InvokeAsync<string>("getEditorValue"); }
catch { ScriptLog.Log(Lang.T("❌ Không đọc được code.", "❌ Failed to read code.")); return; }
// SIM mode: run immediately without confirmation
// REAL mode: show code in dialog for review before executing
if (!State.System.IsSimulation)
{
_pendingCode = code;
var confirmed = await _confirmRunBox!.ShowAsync();
if (confirmed != true) return;
}
if (string.IsNullOrWhiteSpace(code))
{
ScriptLog.Log(Lang.T("⚠️ Không có code.", "⚠️ No code."));
return;
}
_cts = new CancellationTokenSource();
_isRunning = true;
await InvokeAsync(StateHasChanged);
try
{
var resp = await Http.PostAsJsonAsync("/api/script/run",
new { Code = code, Name = _loadedName ?? "" }, _cts.Token);
if ((int)resp.StatusCode == 423)
ScriptLog.Log(Lang.T("⚠ Cần giữ lock (CONTROL ACCESS → TAKE CONTROL) trước khi chạy script.", "⚠ Lock required (CONTROL ACCESS → TAKE CONTROL) before running script."));
else if (!resp.IsSuccessStatusCode)
ScriptLog.Log($"❌ Server: {resp.StatusCode}");
}
catch (OperationCanceledException) { ScriptLog.Log(Lang.T("⛔ Đã dừng.", "⛔ Stopped.")); }
catch (Exception ex) { ScriptLog.Log($"❌ {ex.Message}"); }
finally
{
_isRunning = false;
_cts?.Dispose();
_cts = null;
await InvokeAsync(StateHasChanged);
}
}
private async Task StopScript()
{
_cts?.Cancel();
try { await Http.PostAsync("/api/script/cancel", null); } catch { }
}
// ── Language toggle ───────────────────────────────────────────────────────
private Task ToggleLang() => Lang.ToggleAsync(Http); // OnLangChanged fires setEditorLang
// ── Script save / load ────────────────────────────────────────────────────
private async Task RefreshScriptList()
{
try
{
var list = await Http.GetFromJsonAsync<List<ScriptDto>>("/api/scripts");
_scripts = (list ?? []).Select(s => new ScriptItem(
s.Id, s.Name,
DateTime.TryParse(s.Updated, out var dt)
? dt.ToLocalTime().ToString("dd/MM HH:mm")
: "")).ToList();
await InvokeAsync(StateHasChanged);
}
catch { }
}
private void OpenSave()
{
_saveName = _loadedName ?? "";
_saveOpen = true;
}
private void NewScript()
{
_loadedId = null;
_loadedName = null;
_saveName = "";
_saveOpen = true;
}
private async Task DoSave()
{
if (string.IsNullOrWhiteSpace(_saveName)) return;
string code;
try { code = await JS.InvokeAsync<string>("getEditorValue"); }
catch { return; }
var resp = await Http.PostAsJsonAsync("/api/scripts",
new { Id = _loadedId, Name = _saveName.Trim(), Content = code });
if (resp.IsSuccessStatusCode)
{
var saved = await resp.Content.ReadFromJsonAsync<ScriptDto>();
_loadedId = saved?.Id;
_loadedName = _saveName.Trim();
_saveOpen = false;
await RefreshScriptList();
}
}
private async Task SaveKeyDown(KeyboardEventArgs e)
{
if (e.Key == "Enter") await DoSave();
if (e.Key == "Escape") _saveOpen = false;
}
private async Task LoadScript(ScriptItem item)
{
try
{
var resp = await Http.GetFromJsonAsync<ScriptContentDto>($"/api/scripts/{item.Id}");
if (resp is null) return;
await JS.InvokeVoidAsync("setEditorValue", resp.Content);
_loadedId = item.Id;
_loadedName = item.Name;
await InvokeAsync(StateHasChanged);
}
catch { }
}
private async Task DeleteScript(int id)
{
await Http.DeleteAsync($"/api/scripts/{id}");
if (_loadedId == id) { _loadedId = null; _loadedName = null; }
await RefreshScriptList();
}
record ScriptDto(int Id, string Name, string Updated);
record ScriptContentDto(int Id, string Name, string Content, string Updated);
public async ValueTask DisposeAsync()
{
State.LockStateChanged -= OnStateChanged;
State.SystemChanged -= OnStateChanged;
Lang.LangChanged -= OnLangChanged;
ScriptLog.LogChanged -= OnLogChanged;
_cts?.Cancel();
_cts?.Dispose();
if (_hub != null) await _hub.DisposeAsync();
}
record MeDto(string? UserId, string? Role);
}
<style>
.script-root {
width: 100%;
height: 100%;
display: flex;
flex-direction: column;
background: #27292b;
}
.script-toolbar {
flex-shrink: 0;
min-height: 42px;
background: #27292b;
border-bottom: 1px solid #444;
display: flex;
align-items: center;
gap: 8px;
padding: 0 10px;
}
/* ── body: sidebar + editor side by side ── */
.script-body {
flex: 1;
min-height: 0;
display: flex;
flex-direction: row;
}
/* ── file sidebar ── */
.file-sidebar {
width: 180px;
flex-shrink: 0;
background: #27292b;
border-right: 1px solid #333;
display: flex;
flex-direction: column;
overflow: hidden;
transition: width 0.18s ease;
}
.file-sidebar.collapsed {
width: 0;
border-right: none;
}
.sidebar-header {
display: flex;
align-items: center;
justify-content: space-between;
padding: 7px 10px;
font-size: 10px;
font-weight: 700;
color: #555;
letter-spacing: 0.8px;
border-bottom: 1px solid #252525;
flex-shrink: 0;
}
.sidebar-list {
flex: 1;
overflow-y: auto;
overflow-x: hidden;
}
.sidebar-empty {
padding: 12px 10px;
font-size: 11px;
color: #9CA3AF;
text-align: center;
}
.sidebar-item {
position: relative;
padding: 7px 28px 7px 10px;
cursor: pointer;
border-left: 2px solid transparent;
transition: background 0.1s;
}
.sidebar-item:hover { background: #2f3235; }
.sidebar-item.active {
background: #27292b;
border-left-color: #4a9eff;
}
.sidebar-item-name {
font-size: 12px;
color: #F1F5F9;
font-weight: 500;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
}
.sidebar-item.active .sidebar-item-name { color: #F1F5F9; font-weight: 700; }
.sidebar-item-meta {
font-size: 10px;
color: #9CA3AF;
margin-top: 1px;
}
.sidebar-del-wrap {
position: absolute;
right: 2px;
top: 50%;
transform: translateY(-50%);
opacity: 0;
transition: opacity 0.15s;
}
.sidebar-item:hover .sidebar-del-wrap { opacity: 1; }
.sidebar-del-btn {
color: #9CA3AF !important;
padding: 2px !important;
min-width: 0 !important;
width: 22px !important;
height: 22px !important;
border-radius: 3px !important;
}
.sidebar-del-btn:hover { color: #e74c3c !important; }
.sidebar-toggle {
flex-shrink: 0 !important;
width: 14px !important;
background: #27292b !important;
border: none !important;
border-left: 1px solid #2a2a2a !important;
border-right: 1px solid #2a2a2a !important;
color: #9CA3AF !important;
cursor: pointer !important;
padding: 0 !important;
border-radius: 0 !important;
min-width: 0 !important;
height: 100% !important;
transition: color 0.15s, background 0.15s !important;
}
.sidebar-toggle:hover { color: #4a9eff !important; background: #2f3235 !important; }
/* ── editor + output column ── */
.editor-column {
flex: 1;
min-width: 0;
display: flex;
flex-direction: column;
}
.monaco-editor-host {
flex: 1;
min-height: 0;
width: 100%;
border-bottom: 1px solid #333;
}
.output-resize-handle {
flex-shrink: 0;
height: 5px;
background: #27292b;
cursor: row-resize;
position: relative;
transition: background 0.15s;
}
.output-resize-handle::after {
content: '';
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
width: 36px;
height: 2px;
border-radius: 1px;
background: #2a2a2a;
transition: background 0.15s;
}
.output-resize-handle:hover { background: #27292b; }
.output-resize-handle:hover::after { background: #4a9eff; }
.output-pane {
display: flex;
flex-direction: column;
flex-shrink: 0;
height: 210px;
min-height: 80px;
overflow: hidden;
}
.output-tabs {
flex-shrink: 0;
display: flex;
align-items: center;
background: #27292b;
border-top: 1px solid #222;
border-bottom: 1px solid #1a1a1a;
}
.tab-btn {
padding: 5px 14px !important;
font-size: 11px !important;
color: #9CA3AF !important;
border-bottom: 2px solid transparent !important;
border-radius: 0 !important;
min-height: 0 !important;
height: auto !important;
text-transform: none !important;
font-weight: 400 !important;
letter-spacing: 0 !important;
line-height: 1.4 !important;
transition: color 0.15s !important;
user-select: none;
}
.tab-btn:hover { color: #9CA3AF !important; }
.tab-on { color: #F1F5F9 !important; border-bottom-color: #4a9eff !important; }
.lf-bar {
display: flex;
align-items: center;
gap: 4px;
margin-left: auto;
flex: 1;
min-width: 0;
padding: 0 4px;
}
/* Compact MudTextField inside tab bar */
.lf-field { margin: 0 !important; }
.lf-field .mud-input-root-outlined { height: 22px !important; min-height: 22px !important; }
.lf-field .mud-input-outlined { padding: 0 6px !important; height: 22px !important; font-size: 11px !important; font-family: Consolas, 'Cascadia Code', monospace; color: #9CA3AF !important; }
.lf-field fieldset { top: 0 !important; border-color: #2a2a2a !important; }
.lf-field .mud-input-outlined:focus { color: #F1F5F9 !important; }
.lf-field:focus-within fieldset { border-color: #4a9eff !important; }
.lf-field .mud-input-slot-helper-text { display: none; }
.lf-field input::placeholder { color: #3a3a3a; font-size: 11px; }
.output-area {
flex: 1;
min-height: 0;
background: #27292b;
font-family: Consolas, 'Cascadia Code', monospace;
font-size: 11.5px;
padding: 4px 0;
overflow-y: auto;
word-wrap: break-word;
}
.log-line {
padding: 1.5px 10px;
line-height: 1.55;
border-left: 2px solid transparent;
transition: background 0.1s, border-color 0.1s;
}
.log-line:hover {
background: rgba(255,255,255,0.025);
border-left-color: #2a2a2a;
}
.history-area { font-family: Consolas, monospace; }
.history-row {
display: flex;
align-items: center;
gap: 6px;
padding: 4px 10px;
border-bottom: 1px solid #131313;
transition: background 0.1s;
}
.history-row:hover { background: rgba(255,255,255,0.02); }
.hist-time { color: #9CA3AF; font-size: 10px; min-width: 128px; font-family: Consolas, monospace; flex-shrink: 0; }
.hist-user { color: #4a9eff; font-size: 11px; min-width: 80px; flex-shrink: 0; }
.hist-name { color: #9CA3AF; font-size: 11px; flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
.hist-chip { height: 18px !important; min-height: 18px !important; font-size: 10px !important; padding: 0 6px !important; flex-shrink: 0; }
</style>

View File

@@ -0,0 +1,105 @@
@implements IAsyncDisposable
@inject IJSRuntime JS
<MudPaper Elevation="0" Class="pa-2" Style="background:transparent;">
<MudStack Row="true" AlignItems="AlignItems.Center" Style="cursor:pointer" @onclick="ToggleExpand">
<MudText Typo="Typo.subtitle1">STATUS</MudText>
<MudText Typo="Typo.caption" Style="@($"font-weight:800;letter-spacing:0.5px;margin-left:20px;white-space:nowrap;{WfColor}")">@WfPhaseText</MudText>
@if (State.Workflow.CompletedCycles > 0)
{
<MudText Typo="Typo.caption" Style="color:#5a8a6a;font-weight:700;white-space:nowrap;">@State.Workflow.CompletedCycles ×</MudText>
}
<MudSpacer />
<MudIcon Icon="@(_expanded ? Icons.Material.Filled.ExpandMore : Icons.Material.Filled.ExpandLess)" Size="Size.Small" />
</MudStack>
@if (!string.IsNullOrEmpty(State.Workflow.LastError))
{
<MudAlert Severity="Severity.Error" Dense="true" Class="mt-1" Style="font-size:0.7rem;">@State.Workflow.LastError</MudAlert>
}
@if (_expanded)
{
@* ── IMR + AMR ── *@
<ImrAmrStatusPanel />
<MudDivider Class="mt-2 mb-1" />
@* ── ASRS grid ── *@
<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;
<MudChip T="string" Size="Size.Small"
Color="@(on ? Color.Info : Color.Default)"
Variant="@(on ? Variant.Filled : Variant.Outlined)"
Style="width:100%;margin:0;justify-content:center;height:25px;font-size:13px;font-weight:700;">@cell.Label</MudChip>
}
}
</div>
@* ── Nav ── *@
<MudStack Row="true" Spacing="1" Class="mt-2">
<MudButton Variant="Variant.Outlined" Size="Size.Small" Style="flex:1;min-width:0;padding:0 4px;" OnClick='()=>ScrollTo("p-ctrl")'>CTRL</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" Style="flex:1;min-width:0;padding:0 4px;" OnClick='()=>ScrollTo("p-ops")'>OPS</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" Style="flex:1;min-width:0;padding:0 4px;" OnClick='()=>ScrollTo("p-conveyor")'>CV</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" Style="flex:1;min-width:0;padding:0 4px;" OnClick='()=>ScrollTo("p-imr")'>IMR</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" Style="flex:1;min-width:0;padding:0 4px;" OnClick='()=>ScrollTo("p-amr")'>AMR</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" Style="flex:1;min-width:0;padding:0 4px;" OnClick='()=>ScrollTo("p-dobot")'>Dobot</MudButton>
<MudButton Variant="Variant.Outlined" Size="Size.Small" Style="flex:1;min-width:0;padding:0 4px;" OnClick='()=>ScrollTo("p-asrs")'>ASRS</MudButton>
</MudStack>
}
</MudPaper>
@code {
[Inject] StateService State { get; set; } = default!;
private bool _expanded = true;
void ToggleExpand() => _expanded = !_expanded;
protected override async Task OnInitializedAsync()
{
await State.StartAsync();
State.AsrsChanged += Refresh;
State.WorkflowChanged += Refresh;
}
public ValueTask DisposeAsync()
{
State.AsrsChanged -= Refresh;
State.WorkflowChanged -= Refresh;
return ValueTask.CompletedTask;
}
private void Refresh() => InvokeAsync(StateHasChanged);
private Task ScrollTo(string id) =>
JS.InvokeVoidAsync("eval", $"document.getElementById('{id}')?.scrollIntoView({{behavior:'smooth'}})").AsTask();
private string WfPhaseText
{
get
{
var wf = State.Workflow;
if (!string.IsNullOrEmpty(wf.LastError)) return "ERROR";
if (wf.IsRunning) return "RUNNING";
return "IDLE";
}
}
private string WfColor =>
!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) }),
};
}