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,30 @@
<Project Sdk="Microsoft.NET.Sdk.BlazorWebAssembly">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<HotReloadEnabled>false</HotReloadEnabled>
<!-- Thêm 2 dòng này -->
<BlazorWebAssemblyEnableLinking>true</BlazorWebAssemblyEnableLinking>
<PublishTrimmed>true</PublishTrimmed>
</PropertyGroup>
<ItemGroup>
<!-- Loại bỏ HotReload package khỏi publish -->
<PackageReference Include="Microsoft.AspNetCore.Components.WebAssembly" Version="10.0.6" />
<PackageReference Include="Microsoft.AspNetCore.SignalR.Client" Version="10.0.6" />
<PackageReference Include="MudBlazor" Version="9.3.0" />
<PackageReference Include="System.Security.Cryptography.Xml" Version="10.0.6" />
</ItemGroup>
<!-- Thêm block này để exclude HotReload -->
<ItemGroup>
<BlazorWebAssemblyLazyLoad Remove="Microsoft.DotNet.HotReload.WebAssembly.Browser.dll" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Lab505.Shared\Lab505.Shared.csproj" />
</ItemGroup>
</Project>

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) }),
};
}

24
Lab505.Client/Program.cs Normal file
View File

@@ -0,0 +1,24 @@
using Lab505.Client.Services;
using Microsoft.AspNetCore.Components.WebAssembly.Hosting;
using MudBlazor.Services;
var builder = WebAssemblyHostBuilder.CreateDefault(args);
// ── HTTP client (base address = server origin) ────────────────────────────
builder.Services.AddScoped(sp => new HttpClient
{
BaseAddress = new Uri(builder.HostEnvironment.BaseAddress),
Timeout = System.Threading.Timeout.InfiniteTimeSpan // allow long workflow calls
});
// ── MudBlazor ─────────────────────────────────────────────────────────────
builder.Services.AddMudServices();
// ── Client services ───────────────────────────────────────────────────────
builder.Services.AddScoped<StateService>();
builder.Services.AddScoped<ScriptLogService>();
builder.Services.AddScoped<CommandService>();
builder.Services.AddScoped<ImrInitialPoseService>();
builder.Services.AddScoped<LangService>();
await builder.Build().RunAsync();

View File

@@ -0,0 +1,12 @@
{
"profiles": {
"Lab505.Client": {
"commandName": "Project",
"launchBrowser": true,
"environmentVariables": {
"ASPNETCORE_ENVIRONMENT": "Development"
},
"applicationUrl": "https://localhost:55515;http://localhost:55516"
}
}
}

View File

@@ -0,0 +1,338 @@
using System.Net.Http.Json;
namespace Lab505.Client.Services;
public class CommandService
{
private readonly HttpClient _http;
private readonly ScriptLogService _log;
public CommandService(HttpClient http, ScriptLogService log)
{
_http = http;
_log = log;
}
// ── IMR ───────────────────────────────────────────────────────────────
public Task ImrMoveToAsync(string target, CancellationToken ct = default)
{
_log.LogCommand("IMR", "MoveTo", isMove: true, $"Target={target}");
return PostAsync("/api/imr/vda/move-to", new { Target = target }, ct, "IMR");
}
public Task ImrLoadAsync(CancellationToken ct = default)
{
_log.LogCommand("IMR", "Load");
return PostAsync("/api/imr/vda/load", null, ct, "IMR");
}
public Task ImrUnloadAsync(CancellationToken ct = default)
{
_log.LogCommand("IMR", "Unload");
return PostAsync("/api/imr/vda/unload", null, ct, "IMR");
}
public Task ImrCancelAsync(CancellationToken ct = default)
{
_log.LogCommand("IMR", "Cancel");
return PostAsync("/api/imr/vda/cancel", null, ct, "IMR");
}
public Task ImrPickupAsync(int ok, int ng, CancellationToken ct = default)
{
_log.LogCommand("IMR", "Pickup", @params: $"OK={ok} NG={ng}");
return PostAsync("/api/imr/vda/pickup", new { CountOk = ok, CountNg = ng }, ct, "IMR");
}
public Task ImrUndockAsync(double distance, double velocity, CancellationToken ct = default)
{
_log.LogCommand("IMR", "Undock", isMove: true, $"Dist={distance:F2} Vel={velocity:F2}");
return PostAsync("/api/imr/vda/undock", new { Distance = distance, Velocity = velocity }, ct, "IMR");
}
public Task ImrPauseAsync(CancellationToken ct = default)
{
_log.LogCommand("IMR", "Pause");
return PostAsync("/api/imr/vda/pause", null, ct, "IMR");
}
public Task ImrResumeAsync(CancellationToken ct = default)
{
_log.LogCommand("IMR", "Resume");
return PostAsync("/api/imr/vda/resume", null, ct, "IMR");
}
public Task ImrInitPositionAsync(double x, double y, double theta, CancellationToken ct = default)
{
_log.LogCommand("IMR", "InitPosition", @params: $"X={x:F2} Y={y:F2} θ={theta:F2}");
return PostAsync("/api/imr/vda/init-position", new { X = x, Y = y, Theta = theta }, ct, "IMR");
}
public Task ImrResetOpcAsync(CancellationToken ct = default)
{
_log.LogCommand("IMR", "Reset(OPC)");
return PostAsync("/api/imr/opc/reset", null, ct, "IMR");
}
// ── AMR ───────────────────────────────────────────────────────────────
public Task AmrMoveToAsync(string target, CancellationToken ct = default)
{
_log.LogCommand("AMR", "MoveTo", isMove: true, $"Target={target}");
return PostAsync("/api/amr/vda/move-to", new { Target = target }, ct, "AMR");
}
public Task AmrLoadAsync(CancellationToken ct = default)
{
_log.LogCommand("AMR", "Load");
return PostAsync("/api/amr/vda/load", null, ct, "AMR");
}
public Task AmrUnloadAsync(CancellationToken ct = default)
{
_log.LogCommand("AMR", "Unload");
return PostAsync("/api/amr/vda/unload", null, ct, "AMR");
}
public Task AmrCancelAsync(CancellationToken ct = default)
{
_log.LogCommand("AMR", "Cancel");
return PostAsync("/api/amr/vda/cancel", null, ct, "AMR");
}
public Task AmrUndockAsync(CancellationToken ct = default)
{
_log.LogCommand("AMR", "Undock", isMove: true);
return PostAsync("/api/amr/vda/undock", null, ct, "AMR");
}
public Task AmrPauseAsync(CancellationToken ct = default)
{
_log.LogCommand("AMR", "Pause");
return PostAsync("/api/amr/vda/pause", null, ct, "AMR");
}
public Task AmrResumeAsync(CancellationToken ct = default)
{
_log.LogCommand("AMR", "Resume");
return PostAsync("/api/amr/vda/resume", null, ct, "AMR");
}
public Task AmrInitPositionAsync(double x, double y, double theta, CancellationToken ct = default)
{
_log.LogCommand("AMR", "InitPosition", @params: $"X={x:F2} Y={y:F2} θ={theta:F2}");
return PostAsync("/api/amr/vda/init-position", new { X = x, Y = y, Theta = theta }, ct, "AMR");
}
// ── Conveyor ──────────────────────────────────────────────────────────
public async Task ConveyorSetCoilAsync(string c, string coil, bool state, CancellationToken ct = default)
{
_log.LogConveyorSetCoil(c, coil, state);
var (ok, err) = await PostConveyorAsync($"/api/conveyor/{c}/{coil}", new { State = state }, ct);
_log.LogConveyorWriteResult(c, coil, state, ok, err);
}
// ── Dobot ─────────────────────────────────────────────────────────────
public Task DobotPowerOnAsync(CancellationToken ct = default)
{
_log.LogCommand("Dobot", "PowerOn");
return PostAsync("/api/dobot/power-on", null, ct, "Dobot");
}
public Task DobotGoHomeAsync(CancellationToken ct = default)
{
_log.LogCommand("Dobot", "GoHome");
return PostAsync("/api/dobot/go-home", null, ct, "Dobot");
}
public Task DobotContinueAsync(CancellationToken ct = default)
{
_log.LogCommand("Dobot", "Continue");
return PostAsync("/api/dobot/continue", null, ct, "Dobot");
}
public Task DobotCancelAsync(CancellationToken ct = default)
{
_log.LogCommand("Dobot", "Cancel");
return PostAsync("/api/dobot/cancel", null, ct, "Dobot");
}
// ── ASRS ──────────────────────────────────────────────────────────────
public Task AsrsHomingAsync(CancellationToken ct = default)
{
_log.LogCommand("ASRS", "Homing");
return PostAsync("/api/asrs/homing", null, ct, "ASRS");
}
public Task AsrsWorkflowAsync(string op, CancellationToken ct = default)
{
_log.LogCommand("ASRS", $"Workflow", @params: $"op={op}");
return PostAsync($"/api/asrs/workflow/{op}", null, ct, "ASRS");
}
// ── Workflow ──────────────────────────────────────────────────────────
public Task WorkflowX1AAsync(int times, int ng, CancellationToken ct = default)
{
_log.LogCommand("WF", "X1A", @params: $"Times={times} NG={ng}");
return PostAsync("/api/workflow/x1a", new { Times = times, Ng = ng }, ct, "WF");
}
public Task WorkflowX2AAsync(int times, int ng, CancellationToken ct = default)
{
_log.LogCommand("WF", "X2A", @params: $"Times={times} NG={ng}");
return PostAsync("/api/workflow/x2a", new { Times = times, Ng = ng }, ct, "WF");
}
public Task WorkflowX3AAsync(int times, int ng, CancellationToken ct = default)
{
_log.LogCommand("WF", "X3A", @params: $"Times={times} NG={ng}");
return PostAsync("/api/workflow/x3a", new { Times = times, Ng = ng }, ct, "WF");
}
public Task WorkflowX1BAsync(int times, int ng, CancellationToken ct = default)
{
_log.LogCommand("WF", "X1B", @params: $"Times={times} NG={ng}");
return PostAsync("/api/workflow/x1b", new { Times = times, Ng = ng }, ct, "WF");
}
public Task WorkflowX2BAsync(int times, int ng, CancellationToken ct = default)
{
_log.LogCommand("WF", "X2B", @params: $"Times={times} NG={ng}");
return PostAsync("/api/workflow/x2b", new { Times = times, Ng = ng }, ct, "WF");
}
public Task WorkflowX3BAsync(int times, int ng, CancellationToken ct = default)
{
_log.LogCommand("WF", "X3B", @params: $"Times={times} NG={ng}");
return PostAsync("/api/workflow/x3b", new { Times = times, Ng = ng }, ct, "WF");
}
public Task WorkflowRunCycleAsync(int times, int ng, CancellationToken ct = default)
{
_log.LogCommand("WF", "RunCycle", @params: $"Times={times} NG={ng}");
return PostAsync("/api/workflow/run-cycle", new { Times = times, Ng = ng }, ct, "WF");
}
public Task WorkflowRunStepsAsync(IEnumerable<int> steps, int times, int ng, CancellationToken ct = default)
{
_log.LogCommand("WF", "RunSteps", @params: $"Steps=[{string.Join(",", steps)}] Times={times} NG={ng}");
return PostAsync("/api/workflow/run-steps", new { Steps = steps, Times = times, Ng = ng }, ct, "WF");
}
public Task FlowStepInitAsync(CancellationToken ct = default)
{
_log.LogCommand("WF", "Step:Init");
return PostAsync("/api/workflow/step/init", null, ct, "WF");
}
public Task FlowStepLoadC2Async(CancellationToken ct = default)
{
_log.LogCommand("WF", "Step:LoadC2");
return PostAsync("/api/workflow/step/load-c2", null, ct, "WF");
}
public Task FlowStepToCap1Async(CancellationToken ct = default)
{
_log.LogCommand("WF", "Step:ToCap1");
return PostAsync("/api/workflow/step/to-cap1", null, ct, "WF");
}
public Task FlowStepAmrToImrAsync(CancellationToken ct = default)
{
_log.LogCommand("WF", "Step:AmrToImr");
return PostAsync("/api/workflow/step/amr-to-imr", null, ct, "WF");
}
public Task FlowStepProcessAsync(int times, int ng, CancellationToken ct = default)
{
_log.LogCommand("WF", "Step:Process", @params: $"Times={times} NG={ng}");
return PostAsync("/api/workflow/step/process", new { Times = times, Ng = ng }, ct, "WF");
}
public Task FlowStepImrToAmrAsync(CancellationToken ct = default)
{
_log.LogCommand("WF", "Step:ImrToAmr");
return PostAsync("/api/workflow/step/imr-to-amr", null, ct, "WF");
}
public Task FlowStepToCap2Async(CancellationToken ct = default)
{
_log.LogCommand("WF", "Step:ToCap2");
return PostAsync("/api/workflow/step/to-cap2", null, ct, "WF");
}
public Task FlowStepUnloadC2Async(CancellationToken ct = default)
{
_log.LogCommand("WF", "Step:UnloadC2");
return PostAsync("/api/workflow/step/unload-c2", null, ct, "WF");
}
public Task WorkflowHomeRbAsync(CancellationToken ct = default)
{
_log.LogCommand("WF", "HomeAll");
return PostAsync("/api/workflow/home-rb", null, ct, "WF");
}
public Task WorkflowEmergencyStopAsync()
{
_log.LogCommand("WF", "EMERGENCY STOP");
return PostAsync("/api/workflow/emergency-stop", null, default, "WF");
}
// ── Internal ──────────────────────────────────────────────────────────
private async Task PostAsync(string url, object? body, CancellationToken ct, string? device = null)
{
try
{
var request = new HttpRequestMessage(HttpMethod.Post, url);
if (body != null)
request.Content = JsonContent.Create(body);
var resp = await _http.SendAsync(request, ct);
if (!resp.IsSuccessStatusCode && device != null)
_log.CancelPending(device, $"HTTP {(int)resp.StatusCode}");
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
if (device != null) _log.CancelPending(device, ex.Message);
}
}
/// <summary>Conveyor write — trả về (success, errorMessage).</summary>
private async Task<(bool ok, string? err)> PostConveyorAsync(string url, object? body, CancellationToken ct)
{
try
{
var request = new HttpRequestMessage(HttpMethod.Post, url);
if (body != null)
request.Content = JsonContent.Create(body);
var resp = await _http.SendAsync(request, ct);
var result = await TryReadCommandResultAsync(resp, ct);
if (resp.IsSuccessStatusCode)
return result is { Success: false }
? (false, result.Error ?? "Modbus write failed")
: (true, null);
return (false, result?.Error ?? $"HTTP {(int)resp.StatusCode}");
}
catch (OperationCanceledException) { throw; }
catch (Exception ex) { return (false, ex.Message); }
}
private static async Task<ApiCommandResult?> TryReadCommandResultAsync(HttpResponseMessage resp, CancellationToken ct)
{
if (resp.Content is null)
return null;
try
{
return await resp.Content.ReadFromJsonAsync<ApiCommandResult>(cancellationToken: ct);
}
catch
{
return null;
}
}
private sealed record ApiCommandResult(bool Success, string? Error);
}

View File

@@ -0,0 +1,151 @@
using System.Net.Http.Json;
namespace Lab505.Client.Services;
public sealed class ImrInitialPoseService
{
private const int OperationPollAttempts = 15;
private const int PositionPollAttempts = 20;
private const int PollDelayMs = 300;
private const double PositionTolerance = 0.1;
private readonly HttpClient _http;
private readonly ScriptLogService _log;
public ImrInitialPoseService(HttpClient http, ScriptLogService log)
{
_http = http;
_log = log;
}
public async Task<ImrInitialPoseResult> RunAsync(double x, double y, double yaw, CancellationToken ct = default)
{
_log.LogCommand("IMR", "InitPose(OPC)", isMove: true, $"x={x:F2} y={y:F2} yaw={yaw:F2}");
var operationId = await StartAsync(x, y, yaw, ct);
if (operationId is null)
return new(ImrInitialPoseOutcome.SendFailed);
var operation = await WaitForOperationAsync(operationId, ct);
if (operation.Status == "Failed")
return new(ImrInitialPoseOutcome.OperationFailed, operation.Error);
var position = await WaitForPositionAsync(x, y, ct);
return position.IsMatched
? new(ImrInitialPoseOutcome.Success, ActualX: position.ActualX, ActualY: position.ActualY)
: new(ImrInitialPoseOutcome.PositionMismatch,
ActualX: position.ActualX,
ActualY: position.ActualY,
WaitSeconds: PositionPollAttempts * PollDelayMs / 1000);
}
private async Task<string?> StartAsync(double x, double y, double yaw, CancellationToken ct)
{
try
{
var response = await _http.PostAsJsonAsync("/api/imr/opc/init-pose", new { X = x, Y = y, Yaw = yaw }, ct);
if (!response.IsSuccessStatusCode)
return null;
var body = await response.Content.ReadFromJsonAsync<OperationAcceptedDto>(cancellationToken: ct);
return body?.OperationId;
}
catch (OperationCanceledException)
{
throw;
}
catch
{
return null;
}
}
private async Task<OperationStatusDto> WaitForOperationAsync(string operationId, CancellationToken ct)
{
for (var i = 0; i < OperationPollAttempts; i++)
{
await Task.Delay(PollDelayMs, ct);
try
{
var operation = await _http.GetFromJsonAsync<OperationStatusDto>($"/api/operations/{operationId}", ct);
if (operation?.Status is "Completed" or "Failed")
return operation;
}
catch (OperationCanceledException)
{
throw;
}
catch
{
}
}
return new(operationId, "Completed", null);
}
private async Task<PositionCheckResult> WaitForPositionAsync(double expectedX, double expectedY, CancellationToken ct)
{
double? actualX = null;
double? actualY = null;
for (var i = 0; i < PositionPollAttempts; i++)
{
await Task.Delay(PollDelayMs, ct);
try
{
var status = await _http.GetFromJsonAsync<ImrStatusDto>("/api/imr/status", ct);
if (status is null)
continue;
actualX = status.X_Opc;
actualY = status.Y_Opc;
if (Math.Abs(status.X_Opc - expectedX) <= PositionTolerance &&
Math.Abs(status.Y_Opc - expectedY) <= PositionTolerance)
return new(true, actualX, actualY);
}
catch (OperationCanceledException)
{
throw;
}
catch
{
}
}
return new(false, actualX, actualY);
}
private sealed record OperationAcceptedDto(string OperationId);
private sealed record OperationStatusDto(string Id, string Status, string? Error);
private sealed record ImrStatusDto(
double X_Opc,
double Y_Opc,
double Theta_Opc,
string NavStatus,
string DobotStatus,
string ConveyorStatus,
double X_Vda,
double Y_Vda,
bool IsOnline,
string[] Errors);
private sealed record PositionCheckResult(bool IsMatched, double? ActualX, double? ActualY);
}
public enum ImrInitialPoseOutcome
{
Success,
SendFailed,
OperationFailed,
PositionMismatch
}
public sealed record ImrInitialPoseResult(
ImrInitialPoseOutcome Outcome,
string? Error = null,
double? ActualX = null,
double? ActualY = null,
int WaitSeconds = 0);

View File

@@ -0,0 +1,38 @@
using System.Net.Http.Json;
namespace Lab505.Client.Services;
public class LangService
{
public string Current { get; private set; } = "vi";
public event Action? LangChanged;
public string T(string vi, string en) => Current == "en" ? en : vi;
public void Set(string lang)
{
if (Current == lang) return;
Current = lang;
LangChanged?.Invoke();
}
public async Task LoadAsync(HttpClient http)
{
try
{
var prefs = await http.GetFromJsonAsync<PrefsDto>("/api/prefs");
if (prefs?.Lang is { } l) Set(l);
}
catch { }
}
public async Task ToggleAsync(HttpClient http)
{
Set(Current == "vi" ? "en" : "vi");
try { await http.PutAsJsonAsync("/api/prefs", new { Lang = (string?)Current, NotifMuted = (bool?)null }); }
catch { }
}
private record PrefsDto(string? Lang);
}

View File

@@ -0,0 +1,68 @@
namespace Lab505.Client.Services;
/// <summary>
/// Single source of truth for output-log HTML rendering.
/// Badges: INFO · DONE · ERR · WARN · DEV
/// Columns: [ts]=75px BADGE=46px DEVICE=54px COMMAND=220px STATUS=flexible
/// </summary>
public static class LogFormat
{
// ── Severity colors (MudBlazor-aligned) ──────────────────────────────
public const string CInfo = "#42a5f5"; // INFO blue
public const string CWarn = "#ffa726"; // WARN orange
public const string CSuccess = "#66bb6a"; // DONE green
public const string CError = "#ef5350"; // ERR red
public const string CDev = "#9575cd"; // DEV purple
// ── Column styles ─────────────────────────────────────────────────────
public const string ColTs = "display:inline-block;width:75px;color:#484848";
public const string ColDev = "display:inline-block;width:54px;color:#9e9e9e";
public const string ColCmd = "display:inline-block;width:350px;color:#c8c8c8";
public static string Ts() => DateTime.Now.ToString("HH:mm:ss");
// ── Level → (color, badge) ────────────────────────────────────────────
public static (string color, string badge) LevelBadge(string level) => level switch
{
"success" => (CSuccess, "DONE"),
"error" => (CError, "ERR"),
"warning" => (CWarn, "WARN"),
"dev" => (CDev, "DEV"),
"heartbeat" => (CInfo, "HB"),
_ => (CInfo, "INFO"),
};
// ── Level → status HTML ───────────────────────────────────────────────
public static string LevelStatus(string level) => level switch
{
"success" => $"<span style='color:{CSuccess}'>✓</span>",
"error" => $"<span style='color:{CError}'>✗</span>",
"warning" => $"<span style='color:{CWarn}'>⚠</span>",
_ => "",
};
/// <summary>5-column line: [ts] BADGE DEVICE COMMAND STATUS │ detail</summary>
public static string Line(string color, string badge, string device, string command, string status, string? detail = null)
{
var badgeStyle = $"display:inline-block;width:46px;color:{color};font-weight:700";
var detPart = detail != null
? $"<span style='color:#606060'> │ </span><span style='color:#a0a0a0'>{detail}</span>"
: "";
return $"<span style='{ColTs}'>[{Ts()}]</span>" +
$"<span style='{badgeStyle}'>{badge}</span>" +
$"<span style='{ColDev}'>{device}</span>" +
$"<span style='{ColCmd}'>{command}</span>" +
$"<span style='color:#c8c8c8'>{status}</span>" +
detPart;
}
/// <summary>3-column line for DEV state changes: [ts] BADGE DEVICE message</summary>
public static string LineRaw(string color, string badge, string device, string msg)
{
var badgeStyle = $"display:inline-block;width:46px;color:{color};font-weight:700";
return $"<span style='{ColTs}'>[{Ts()}]</span>" +
$"<span style='{badgeStyle}'>{badge}</span>" +
$"<span style='{ColDev}'>{device}</span>" +
$"<span style='color:#c8c8c8'>{msg}</span>";
}
}

View File

@@ -0,0 +1,794 @@
using Lab505.Shared;
namespace Lab505.Client.Services;
/// <summary>
/// Singleton (per WASM session) log bus.
/// Mỗi lệnh sinh ra tối đa 3 dòng:
/// 1. → gửi (ngay khi CommandService gọi LogCommand)
/// 2. ✓ robot nhận (khi NBR đổi sang true hoặc busy bắt đầu)
/// 3. ✓ hoàn thành / ✗ lỗi (khi busy trở về false hoặc action FINISHED/FAILED)
/// </summary>
public class ScriptLogService : IDisposable
{
private readonly StateService _state;
private readonly LangService _lang;
private readonly List<string> _lines = new();
private readonly System.Timers.Timer _timeoutTimer;
private const int TimeoutSeconds = 1200; // 20 phút
// Aliases → LogFormat (single source of truth)
private const string CInfo = LogFormat.CInfo;
private const string CWarn = LogFormat.CWarn;
private const string CSuccess = LogFormat.CSuccess;
private const string CError = LogFormat.CError;
private const string CDev = LogFormat.CDev;
public IReadOnlyList<string> Lines => _lines;
public event Action? LogChanged;
public void Clear()
{
_lines.Clear();
LogChanged?.Invoke();
}
// ── Pending command per device ────────────────────────────────────────
private PendingCmd? _imrPending;
private PendingCmd? _amrPending;
private PendingCmd? _dobotPending;
private PendingCmd? _asrsPending;
private PendingCmd? _wfPending;
private PendingConveyorCmd? _conveyorPending;
private bool? _conveyorTargetPrev;
// Last command sent per robot (for NBR context after pending clears)
private string? _lastImrCmd;
private string? _lastAmrCmd;
// ── Previous state snapshots (for delta detection) ────────────────────
private bool? _prevImrNBR;
private bool? _prevAmrNBR;
private bool _prevImrBusy;
private bool _prevAmrBusy;
private bool _prevDobotBusy;
private bool _prevAsrsBusy;
private bool _prevWfRunning;
private string? _prevImrErr;
private string? _prevAmrErr;
private string? _prevDobotErr;
private string? _prevAsrsErr;
private string? _prevWfErr;
private string? _prevImrActionId;
private string? _prevImrActionStatus;
private string? _prevAmrActionId;
private string? _prevAmrActionStatus;
private string? _prevConveyorWriteError;
// ── Dev mode ──────────────────────────────────────────────────────────
public bool IsDevMode { get; set; }
private bool? _devImrNBR, _devAmrNBR;
private bool _devImrOnline, _devAmrOnline;
private string? _devImrActId, _devImrActStatus;
private string? _devAmrActId, _devAmrActStatus;
private bool _devImrBusy, _devAmrBusy, _devDobotBusy, _devAsrsBusy;
private bool _devWfRunning;
private bool? _devAsrsSafety, _devAsrsOffline;
// Conveyor coils
private bool? _devC1In, _devC1Out, _devC1IMRin, _devC1IMRout;
private bool? _devC1HasGoods, _devC1NotGoods, _devC1Ready;
private bool? _devC2In, _devC2Out, _devC2HasGoods, _devC2NotGoods, _devC2Ready;
// ASRS slots
private bool? _devX11, _devX12, _devX13;
private bool? _devX21, _devX22, _devX23;
private bool? _devX31, _devX32, _devX33;
private bool? _devX41, _devX42, _devX43;
public ScriptLogService(StateService state, LangService lang)
{
_state = state;
_lang = lang;
state.ImrChanged += OnImrChanged;
state.AmrChanged += OnAmrChanged;
state.WorkflowChanged += OnWorkflowChanged;
state.AsrsChanged += OnAsrsChanged;
state.ConveyorChanged += OnConveyorChanged;
// snapshot initial state
_prevImrNBR = state.Imr.NewBaseRequest;
_prevAmrNBR = state.Amr.NewBaseRequest;
_prevImrBusy = state.Workflow.ImrBusy;
_prevAmrBusy = state.Workflow.AmrBusy;
_prevDobotBusy = state.Workflow.DobotBusy;
_prevAsrsBusy = state.Asrs.IsBusy;
_prevWfRunning = state.Workflow.IsRunning;
_prevImrErr = state.Workflow.ImrExecError;
_prevAmrErr = state.Workflow.AmrExecError;
_prevDobotErr = state.Workflow.DobotExecError;
_prevAsrsErr = state.Asrs.LastError;
_prevWfErr = state.Workflow.LastError;
_prevConveyorWriteError = state.Conveyor.WriteError;
// Dev snapshots
var _di = state.Imr; var _da = state.Amr; var _dw = state.Workflow;
var _ds = state.Asrs; var _dc = state.Conveyor;
_devImrNBR = _di.NewBaseRequest; _devAmrNBR = _da.NewBaseRequest;
_devImrOnline = _di.IsOnline; _devAmrOnline = _da.IsOnline;
_devImrActId = _di.Actions.Length > 0 ? _di.Actions[0].ActionID : null;
_devImrActStatus = _di.Actions.Length > 0 ? _di.Actions[0].ActionStatus : null;
_devAmrActId = _da.Actions.Length > 0 ? _da.Actions[0].ActionID : null;
_devAmrActStatus = _da.Actions.Length > 0 ? _da.Actions[0].ActionStatus : null;
_devImrBusy = _dw.ImrBusy; _devAmrBusy = _dw.AmrBusy; _devDobotBusy = _dw.DobotBusy;
_devAsrsBusy = _ds.IsBusy; _devWfRunning = _dw.IsRunning;
_devAsrsSafety = _ds.SAFETY_MODE; _devAsrsOffline = _ds.IsOffline;
_devC1In = _dc.C1In; _devC1Out = _dc.C1Out; _devC1IMRin = _dc.C1IMRin; _devC1IMRout = _dc.C1IMRout;
_devC1HasGoods = _dc.C1HasGoods; _devC1NotGoods = _dc.C1NotGoods; _devC1Ready = _dc.C1Ready;
_devC2In = _dc.C2In; _devC2Out = _dc.C2Out;
_devC2HasGoods = _dc.C2HasGoods; _devC2NotGoods = _dc.C2NotGoods; _devC2Ready = _dc.C2Ready;
_devX11 = _ds.X11; _devX12 = _ds.X12; _devX13 = _ds.X13;
_devX21 = _ds.X21; _devX22 = _ds.X22; _devX23 = _ds.X23;
_devX31 = _ds.X31; _devX32 = _ds.X32; _devX33 = _ds.X33;
_devX41 = _ds.X41; _devX42 = _ds.X42; _devX43 = _ds.X43;
_timeoutTimer = new System.Timers.Timer(15_000);
_timeoutTimer.Elapsed += (_, _) => CheckTimeouts();
_timeoutTimer.AutoReset = true;
_timeoutTimer.Start();
}
public void Dispose()
{
_timeoutTimer.Dispose();
}
// ── Timeout check ─────────────────────────────────────────────────────
private void CheckTimeouts()
{
var now = DateTime.Now;
if (_imrPending != null && (now - _imrPending.SentAt).TotalSeconds > TimeoutSeconds)
CancelPending("IMR", _lang.T("⏱ không phản hồi", "⏱ no response"));
if (_amrPending != null && (now - _amrPending.SentAt).TotalSeconds > TimeoutSeconds)
CancelPending("AMR", _lang.T("⏱ không phản hồi", "⏱ no response"));
if (_dobotPending != null && (now - _dobotPending.SentAt).TotalSeconds > TimeoutSeconds)
CancelPending("Dobot", _lang.T("⏱ không phản hồi", "⏱ no response"));
if (_asrsPending != null && (now - _asrsPending.SentAt).TotalSeconds > TimeoutSeconds)
CancelPending("ASRS", _lang.T("⏱ không phản hồi", "⏱ no response"));
if (_wfPending != null && (now - _wfPending.SentAt).TotalSeconds > TimeoutSeconds)
CancelPending("WF", _lang.T("⏱ không phản hồi", "⏱ no response"));
}
// ── Cancel pending (HTTP error hoặc timeout) ──────────────────────────
public void CancelPending(string device, string reason)
{
PendingCmd? p = device switch
{
"IMR" => _imrPending,
"AMR" => _amrPending,
"Dobot" => _dobotPending,
"ASRS" => _asrsPending,
"WF" => _wfPending,
_ => null
};
if (p == null) return;
Push(Line(CError, "ERR", device, p.Command, _lang.T("✗ lỗi", "✗ error"), reason));
switch (device)
{
case "IMR": _imrPending = null; break;
case "AMR": _amrPending = null; break;
case "Dobot": _dobotPending = null; break;
case "ASRS": _asrsPending = null; break;
case "WF": _wfPending = null; break;
}
}
// ── Raw line (script hub hoặc caller khác) ────────────────────────────
public void Log(string htmlLine)
{
_lines.Insert(0, htmlLine);
Trim();
LogChanged?.Invoke();
}
public void LogNotification(NotificationDto notification)
{
var (color, badge) = LogFormat.LevelBadge(notification.Level);
var status = LogFormat.LevelStatus(notification.Level);
var source = string.IsNullOrWhiteSpace(notification.Source)
? TryExtractSource(notification.Message)
: notification.Source;
var device = MapNotificationDevice(source);
var command = string.IsNullOrWhiteSpace(notification.Command)
? notification.Message
: notification.Command!;
var detail = notification.Detail;
Log(Line(color, badge, device, command, status, detail));
if (IsDevMode && ShouldCaptureSystemSnapshot(notification, source))
LogSystemSnapshot($"{device}:{command}");
}
// ── Ghi lệnh vừa gửi ─────────────────────────────────────────────────
public void LogCommand(string device, string command, bool isMove = false, string? @params = null)
{
Push(Line(CInfo, "INFO", device, command, _lang.T("→ gửi", "→ sent"), @params));
var wf = _state.Workflow;
var imr = _state.Imr;
var amr = _state.Amr;
switch (device)
{
case "IMR":
_lastImrCmd = command;
_imrPending = new(command, @params, isMove, DateTime.Now);
_prevImrNBR = imr.NewBaseRequest;
_prevImrErr = wf.ImrExecError;
_prevImrActionId = imr.Actions.Length > 0 ? imr.Actions[0].ActionID : null;
_prevImrActionStatus = imr.Actions.Length > 0 ? imr.Actions[0].ActionStatus : null;
break;
case "AMR":
_lastAmrCmd = command;
_amrPending = new(command, @params, isMove, DateTime.Now);
_prevAmrNBR = amr.NewBaseRequest;
_prevAmrErr = wf.AmrExecError;
_prevAmrActionId = amr.Actions.Length > 0 ? amr.Actions[0].ActionID : null;
_prevAmrActionStatus = amr.Actions.Length > 0 ? amr.Actions[0].ActionStatus : null;
break;
case "Dobot":
_dobotPending = new(command, @params, false, DateTime.Now);
_prevDobotErr = wf.DobotExecError;
break;
case "ASRS":
_asrsPending = new(command, @params, false, DateTime.Now);
_prevAsrsErr = _state.Asrs.LastError;
break;
case "WF":
if (command != "EMERGENCY STOP" && !IsXCycleCommand(command))
{
_wfPending = new(command, @params, false, DateTime.Now);
_prevWfErr = wf.LastError;
}
break;
}
}
public void LogConveyorSetCoil(string c, string coil, bool expectedValue)
{
var key = c + coil;
Push(Line(CInfo, "INFO", "CV", "SetCoil", _lang.T("→ gửi", "→ sent"), $"{key}={expectedValue}"));
_conveyorPending = new(key, expectedValue);
_conveyorTargetPrev = GetCoil(_state.Conveyor, key);
_prevConveyorWriteError = _state.Conveyor.WriteError;
}
public void LogConveyorWriteResult(string c, string coil, bool expectedValue, bool ok, string? error)
{
var key = c + coil;
if (ok)
Push(Line(CSuccess, "DONE", "CV", "SetCoil", _lang.T("✓ PLC write OK", "✓ PLC write OK"), $"{key}={expectedValue}"));
else
Push(Line(CError, "ERR", "CV", "SetCoil", _lang.T("✗ write error", "✗ write error"), $"{key}={expectedValue} | {error}"));
if (!ok) _conveyorPending = null;
}
// ── State handlers ────────────────────────────────────────────────────
private void OnImrChanged()
{
var imr = _state.Imr;
if (_imrPending != null)
{
if (imr.NewBaseRequest == true && _prevImrNBR != true)
Push(Line(CWarn, "WARN", "IMR", _imrPending.Command, "✓ New Base Request"));
if (imr.Actions.Length > 0)
{
var a = imr.Actions[0];
if (a.ActionID != _prevImrActionId || a.ActionStatus != _prevImrActionStatus)
{
var statusStr = a.ActionStatus ?? "?";
if (statusStr is "RUNNING" or "INITIALIZING")
Push(Line(CWarn, "WARN", "IMR", _imrPending.Command, $"action {a.ActionID}", statusStr));
else if (statusStr == "FINISHED")
Push(Line(CSuccess, "DONE", "IMR", _imrPending.Command, $"action {a.ActionID}", _lang.T("hoàn thành", "done")));
else if (statusStr is "FAILED" or "FAILED_FATAL")
Push(Line(CError, "ERR", "IMR", _imrPending.Command, $"action {a.ActionID}", _lang.T("thất bại", "failed")));
_prevImrActionId = a.ActionID;
_prevImrActionStatus = a.ActionStatus;
}
}
}
_prevImrNBR = imr.NewBaseRequest;
if (IsDevMode)
{
bool noPending = _imrPending == null;
if (imr.IsOnline != _devImrOnline)
{ DevPush("IMR", $"online={imr.IsOnline}"); _devImrOnline = imr.IsOnline; }
if (imr.NewBaseRequest != _devImrNBR)
{
if (noPending)
DevPush("IMR", _lastImrCmd ?? "", $"New Base Request={imr.NewBaseRequest}");
_devImrNBR = imr.NewBaseRequest;
}
if (imr.Actions.Length > 0)
{
var a = imr.Actions[0];
if (a.ActionID != _devImrActId || a.ActionStatus != _devImrActStatus)
{ if (noPending) DevPush("IMR", a.ActionID ?? "", a.ActionStatus ?? "?"); _devImrActId = a.ActionID; _devImrActStatus = a.ActionStatus; }
}
else if (_devImrActId != null)
{ if (noPending) DevPush("IMR", "actions cleared"); _devImrActId = null; _devImrActStatus = null; }
}
}
private void OnAmrChanged()
{
var amr = _state.Amr;
if (_amrPending != null)
{
if (amr.NewBaseRequest == true && _prevAmrNBR != true)
Push(Line(CWarn, "WARN", "AMR", _amrPending.Command, "✓ New Base Request"));
if (amr.Actions.Length > 0)
{
var a = amr.Actions[0];
if (a.ActionID != _prevAmrActionId || a.ActionStatus != _prevAmrActionStatus)
{
var statusStr = a.ActionStatus ?? "?";
if (statusStr is "RUNNING" or "INITIALIZING")
Push(Line(CWarn, "WARN", "AMR", _amrPending.Command, $"action {a.ActionID}", statusStr));
else if (statusStr == "FINISHED")
Push(Line(CSuccess, "DONE", "AMR", _amrPending.Command, $"action {a.ActionID}", _lang.T("hoàn thành", "done")));
else if (statusStr is "FAILED" or "FAILED_FATAL")
Push(Line(CError, "ERR", "AMR", _amrPending.Command, $"action {a.ActionID}", _lang.T("thất bại", "failed")));
_prevAmrActionId = a.ActionID;
_prevAmrActionStatus = a.ActionStatus;
}
}
}
_prevAmrNBR = amr.NewBaseRequest;
if (IsDevMode)
{
bool noPending = _amrPending == null;
if (amr.IsOnline != _devAmrOnline)
{ DevPush("AMR", $"online={amr.IsOnline}"); _devAmrOnline = amr.IsOnline; }
if (amr.NewBaseRequest != _devAmrNBR)
{
if (noPending)
DevPush("AMR", _lastAmrCmd ?? "", $"New Base Request={amr.NewBaseRequest}");
_devAmrNBR = amr.NewBaseRequest;
}
if (amr.Actions.Length > 0)
{
var a = amr.Actions[0];
if (a.ActionID != _devAmrActId || a.ActionStatus != _devAmrActStatus)
{ if (noPending) DevPush("AMR", a.ActionID ?? "", a.ActionStatus ?? "?"); _devAmrActId = a.ActionID; _devAmrActStatus = a.ActionStatus; }
}
else if (_devAmrActId != null)
{ if (noPending) DevPush("AMR", "actions cleared"); _devAmrActId = null; _devAmrActStatus = null; }
}
}
private void OnWorkflowChanged()
{
var wf = _state.Workflow;
// ── IMR busy ──────────────────────────────────────────────────────
if (_imrPending != null)
{
if (!_prevImrBusy && wf.ImrBusy)
{
var fromPos = _imrPending.IsMove ? $"from x={_state.Imr.X:F2} y={_state.Imr.Y:F2}" : null;
Push(Line(CWarn, "WARN", "IMR", _imrPending.Command, _lang.T("đang thực hiện", "executing"), fromPos));
}
else if (_prevImrBusy && !wf.ImrBusy)
{
var newErr = wf.ImrExecError != null && wf.ImrExecError != _prevImrErr ? wf.ImrExecError : null;
if (newErr != null)
Push(Line(CError, "ERR", "IMR", _imrPending.Command, newErr));
else
{
var elapsed = $"{(DateTime.Now - _imrPending.SentAt).TotalSeconds:F1}s";
var pos = _imrPending.IsMove ? $"x={_state.Imr.X:F2} y={_state.Imr.Y:F2}" : null;
var detail = pos != null ? $"{elapsed} │ {pos}" : elapsed;
Push(Line(CSuccess, "DONE", "IMR", _imrPending.Command, _lang.T("hoàn thành", "done"), detail));
}
_imrPending = null;
}
}
// ── AMR busy ──────────────────────────────────────────────────────
if (_amrPending != null)
{
if (!_prevAmrBusy && wf.AmrBusy)
{
var fromPos = _amrPending.IsMove ? $"from x={_state.Amr.X:F2} y={_state.Amr.Y:F2}" : null;
Push(Line(CWarn, "WARN", "AMR", _amrPending.Command, _lang.T("đang thực hiện", "executing"), fromPos));
}
else if (_prevAmrBusy && !wf.AmrBusy)
{
var newErr = wf.AmrExecError != null && wf.AmrExecError != _prevAmrErr ? wf.AmrExecError : null;
if (newErr != null)
Push(Line(CError, "ERR", "AMR", _amrPending.Command, newErr));
else
{
var elapsed = $"{(DateTime.Now - _amrPending.SentAt).TotalSeconds:F1}s";
var pos = _amrPending.IsMove ? $"x={_state.Amr.X:F2} y={_state.Amr.Y:F2}" : null;
var detail = pos != null ? $"{elapsed} │ {pos}" : elapsed;
Push(Line(CSuccess, "DONE", "AMR", _amrPending.Command, _lang.T("hoàn thành", "done"), detail));
}
_amrPending = null;
}
}
// ── Dobot busy ────────────────────────────────────────────────────
if (_dobotPending != null)
{
if (!_prevDobotBusy && wf.DobotBusy)
{
Push(Line(CWarn, "WARN", "Dobot", _dobotPending.Command, _lang.T("đang thực hiện", "executing")));
}
else if (_prevDobotBusy && !wf.DobotBusy)
{
var newErr = wf.DobotExecError != null && wf.DobotExecError != _prevDobotErr ? wf.DobotExecError : null;
if (newErr != null)
Push(Line(CError, "ERR", "Dobot", _dobotPending.Command, newErr));
else
{
var elapsed = $"{(DateTime.Now - _dobotPending.SentAt).TotalSeconds:F1}s";
Push(Line(CSuccess, "DONE", "Dobot", _dobotPending.Command, _lang.T("hoàn thành", "done"), elapsed));
}
_dobotPending = null;
}
}
// ── Workflow cycle ────────────────────────────────────────────────
if (_wfPending != null)
{
if (!_prevWfRunning && wf.IsRunning)
{
Push(Line(CWarn, "WARN", "WF", _wfPending.Command, _lang.T("đang chạy", "running")));
}
else if (_prevWfRunning && !wf.IsRunning)
{
var newErr = wf.LastError != null && wf.LastError != _prevWfErr ? wf.LastError : null;
if (newErr != null)
Push(Line(CError, "ERR", "WF", _wfPending.Command, newErr));
else
{
var elapsed = $"{(DateTime.Now - _wfPending.SentAt).TotalSeconds:F1}s";
Push(Line(CSuccess, "DONE", "WF", _wfPending.Command, _lang.T("hoàn thành", "done"), $"{elapsed} │ cycles={wf.CompletedCycles}"));
}
_wfPending = null;
}
}
_prevImrBusy = wf.ImrBusy;
_prevAmrBusy = wf.AmrBusy;
_prevDobotBusy = wf.DobotBusy;
_prevWfRunning = wf.IsRunning;
_prevImrErr = wf.ImrExecError;
_prevAmrErr = wf.AmrExecError;
_prevDobotErr = wf.DobotExecError;
_prevWfErr = wf.LastError;
if (IsDevMode)
{
if (wf.IsRunning != _devWfRunning)
{
DevPush("WF", wf.IsRunning ? "started" : "stopped");
LogSystemSnapshot(wf.IsRunning ? "wf-start" : "wf-stop");
_devWfRunning = wf.IsRunning;
}
if (wf.ImrBusy != _devImrBusy)
{ if (_imrPending == null) DevPush("IMR", $"busy={wf.ImrBusy}" + (wf.ImrBusyLabel != null ? $" [{wf.ImrBusyLabel}]" : "")); _devImrBusy = wf.ImrBusy; }
if (wf.AmrBusy != _devAmrBusy)
{ if (_amrPending == null) DevPush("AMR", $"busy={wf.AmrBusy}" + (wf.AmrBusyLabel != null ? $" [{wf.AmrBusyLabel}]" : "")); _devAmrBusy = wf.AmrBusy; }
if (wf.DobotBusy != _devDobotBusy)
{ if (_dobotPending == null) DevPush("Dobot", $"busy={wf.DobotBusy}" + (wf.DobotBusyLabel != null ? $" [{wf.DobotBusyLabel}]" : "")); _devDobotBusy = wf.DobotBusy; }
}
}
private void OnAsrsChanged()
{
var asrs = _state.Asrs;
if (_asrsPending != null)
{
if (!_prevAsrsBusy && asrs.IsBusy)
{
Push(Line(CWarn, "WARN", "ASRS", _asrsPending.Command, _lang.T("đang thực hiện", "executing")));
}
else if (_prevAsrsBusy && !asrs.IsBusy)
{
var newErr = asrs.LastError != null && asrs.LastError != _prevAsrsErr ? asrs.LastError : null;
if (newErr != null)
Push(Line(CError, "ERR", "ASRS", _asrsPending.Command, newErr));
else
{
var elapsed = $"{(DateTime.Now - _asrsPending.SentAt).TotalSeconds:F1}s";
Push(Line(CSuccess, "DONE", "ASRS", _asrsPending.Command, _lang.T("hoàn thành", "done"), elapsed));
}
_asrsPending = null;
}
}
_prevAsrsBusy = asrs.IsBusy;
_prevAsrsErr = asrs.LastError;
if (IsDevMode)
{
if (asrs.IsBusy != _devAsrsBusy)
{ DevPush("ASRS", $"busy={asrs.IsBusy}"); _devAsrsBusy = asrs.IsBusy; }
if (asrs.SAFETY_MODE != _devAsrsSafety)
{
DevPush("ASRS", $"safety={asrs.SAFETY_MODE}");
LogSystemSnapshot($"asrs-safety={FormatBool(asrs.SAFETY_MODE)}");
_devAsrsSafety = asrs.SAFETY_MODE;
}
DevSlot("X11", asrs.X11, ref _devX11); DevSlot("X12", asrs.X12, ref _devX12); DevSlot("X13", asrs.X13, ref _devX13);
DevSlot("X21", asrs.X21, ref _devX21); DevSlot("X22", asrs.X22, ref _devX22); DevSlot("X23", asrs.X23, ref _devX23);
DevSlot("X31", asrs.X31, ref _devX31); DevSlot("X32", asrs.X32, ref _devX32); DevSlot("X33", asrs.X33, ref _devX33);
DevSlot("X41", asrs.X41, ref _devX41); DevSlot("X42", asrs.X42, ref _devX42); DevSlot("X43", asrs.X43, ref _devX43);
}
}
private void OnConveyorChanged()
{
var conv = _state.Conveyor;
if (IsDevMode)
{
var pendingKey = _conveyorPending?.CoilKey; // skip coil already tracked by pending section
DevCoil("C1.In", conv.C1In, ref _devC1In, pendingKey);
DevCoil("C1.Out", conv.C1Out, ref _devC1Out, pendingKey);
DevCoil("C1.IMRin", conv.C1IMRin, ref _devC1IMRin, pendingKey);
DevCoil("C1.IMRout", conv.C1IMRout, ref _devC1IMRout, pendingKey);
DevCoil("C1.Goods", conv.C1HasGoods, ref _devC1HasGoods, pendingKey);
DevCoil("C1.Empty", conv.C1NotGoods, ref _devC1NotGoods, pendingKey);
DevCoil("C1.Ready", conv.C1Ready, ref _devC1Ready, pendingKey);
DevCoil("C2.In", conv.C2In, ref _devC2In, pendingKey);
DevCoil("C2.Out", conv.C2Out, ref _devC2Out, pendingKey);
DevCoil("C2.Goods", conv.C2HasGoods, ref _devC2HasGoods, pendingKey);
DevCoil("C2.Empty", conv.C2NotGoods, ref _devC2NotGoods, pendingKey);
DevCoil("C2.Ready", conv.C2Ready, ref _devC2Ready, pendingKey);
}
if (_conveyorPending == null) return;
var key = _conveyorPending.CoilKey;
var current = GetCoil(conv, key);
var prev = _conveyorTargetPrev;
if (current.HasValue)
{
if (_conveyorPending.ExpectedValue)
{
if (!_conveyorPending.CoilReached && current.Value)
{
Push(Line(CWarn, "WARN", "CV", "SetCoil", $"{key}=true"));
_conveyorPending = _conveyorPending with { CoilReached = true };
}
else if (_conveyorPending.CoilReached && !current.Value)
{
Push(Line(CSuccess, "DONE", "CV", "SetCoil", $"{key} reset"));
_conveyorPending = null;
}
}
else
{
if (prev != false && !current.Value)
{
Push(Line(CSuccess, "DONE", "CV", "SetCoil", $"{key}=false"));
_conveyorPending = null;
}
}
_conveyorTargetPrev = current;
}
}
private static bool? GetCoil(ConveyorPushDto conv, string key) =>
key.ToLowerInvariant().Replace("-", "") switch
{
"c1in" => conv.C1In,
"c1out" => conv.C1Out,
"c1imrin" => conv.C1IMRin,
"c1imrout" => conv.C1IMRout,
"c1hasgoods" => conv.C1HasGoods,
"c1notgoods" => conv.C1NotGoods,
"c1ready" => conv.C1Ready,
"c2in" => conv.C2In,
"c2out" => conv.C2Out,
"c2hasgoods" => conv.C2HasGoods,
"c2notgoods" => conv.C2NotGoods,
"c2ready" => conv.C2Ready,
_ => null
};
// ── Dev helpers ───────────────────────────────────────────────────────
/// <summary>DEV line without a specific command (state change, online, busy…).</summary>
private void DevPush(string device, string msg) =>
Push(LineRaw(CDev, "DEV", device, msg));
/// <summary>DEV line with command context (NBR, action status…).</summary>
private void DevPush(string device, string command, string status) =>
Push(Line(CDev, "DEV", device, command, status));
private void DevCoil(string name, bool? current, ref bool? prev, string? pendingKey = null)
{
if (current == prev) return;
var key = name.Replace(".", "").Replace("IMR", "imr").ToLowerInvariant();
if (pendingKey == null || !pendingKey.Equals(key, StringComparison.OrdinalIgnoreCase))
Push(LineRaw(CDev, "DEV", "CV", $"{name}={current}"));
prev = current;
}
private void DevSlot(string name, bool? current, ref bool? prev)
{
if (current == prev) return;
Push(LineRaw(CDev, "DEV", "ASRS", $"{name}={current}"));
prev = current;
}
// ── Helpers ───────────────────────────────────────────────────────────
private void LogSystemSnapshot(string trigger)
{
var mode = _state.System.IsSimulation ? "SIM" : "REAL";
var wf = _state.Workflow;
var imr = _state.Imr;
var amr = _state.Amr;
var conv = _state.Conveyor;
var asrs = _state.Asrs;
DevPush("SYS",
$"snapshot={trigger} | mode={mode} | wf={DescribeWorkflow(wf)}");
DevPush("SYS",
$"IMR[{DescribeRobot(imr)}] | AMR[{DescribeRobot(amr)}] | CV[{DescribeConveyor(conv)}] | ASRS[{DescribeAsrs(asrs)}]");
}
private static bool ShouldCaptureSystemSnapshot(NotificationDto notification, string? source)
{
if (notification.Level is "warning" or "error")
return true;
var normalized = (source ?? notification.Source ?? string.Empty).ToUpperInvariant();
if (normalized.Contains("FLOW") || normalized == "WF")
{
var command = notification.Command ?? notification.Message;
return command.Contains("Start", StringComparison.OrdinalIgnoreCase)
|| command.Contains("Done", StringComparison.OrdinalIgnoreCase)
|| command.Contains("Hủy", StringComparison.OrdinalIgnoreCase)
|| command.Contains("Cancel", StringComparison.OrdinalIgnoreCase);
}
return false;
}
private static string? TryExtractSource(string message)
{
if (string.IsNullOrWhiteSpace(message))
return null;
var text = message.Trim();
if (text.StartsWith('['))
{
var end = text.IndexOf(']');
if (end > 1)
return text[1..end].Trim();
}
var colon = text.IndexOf(": ", StringComparison.Ordinal);
if (colon > 0)
{
var head = text[..colon].Trim();
if (head.Length <= 24)
return head;
}
return null;
}
private static string MapNotificationDevice(string? source)
{
if (string.IsNullOrWhiteSpace(source))
return "Sys";
var prefix = source.Trim().ToUpperInvariant();
return prefix switch
{
"IMR" => "IMR",
"AMR" => "AMR",
"DOBOT" => "Dobot",
"ASRS" => "ASRS",
"WF" or "FLOW" => "WF",
"OPC" => "OPC",
"VDA" => "VDA",
"SIM" => "Sim",
"T3" => "T3",
"WAIT" => "Wait",
"INIT" => "Init",
var p when p.StartsWith("FLOW+ASRS") => "WF+AS",
var p when p.StartsWith("CONV") => "Conv",
var p when p.StartsWith("CONVEYOR") => "Conv",
var p when p.StartsWith("STEP") => "WF",
var p => p.Length > 6 ? p[..6] : p,
};
}
private static string DescribeWorkflow(WorkflowStateDto workflow)
{
var state = workflow.IsRunning ? "running" : "idle";
var last = string.IsNullOrWhiteSpace(workflow.LastError) ? "ok" : $"err={workflow.LastError}";
return $"{state} cycles={workflow.CompletedCycles} imrBusy={workflow.ImrBusy} amrBusy={workflow.AmrBusy} dobotBusy={workflow.DobotBusy} {last}";
}
private static string DescribeRobot(RobotStateDto robot)
{
var action = robot.Actions.Length > 0
? $"{robot.Actions[0].ActionID}/{robot.Actions[0].ActionStatus ?? "?"}"
: "-";
var errors = robot.Errors.Count > 0 ? robot.Errors.Count.ToString() : "0";
return $"on={robot.IsOnline} nbr={FormatBool(robot.NewBaseRequest)} pos=({robot.X:F2},{robot.Y:F2}) act={action} err={errors}";
}
private static string DescribeConveyor(ConveyorPushDto conveyor)
=> $"C1[in={FormatBool(conveyor.C1In)},out={FormatBool(conveyor.C1Out)},goods={FormatBool(conveyor.C1HasGoods)},empty={FormatBool(conveyor.C1NotGoods)},ready={FormatBool(conveyor.C1Ready)}] " +
$"C2[in={FormatBool(conveyor.C2In)},out={FormatBool(conveyor.C2Out)},goods={FormatBool(conveyor.C2HasGoods)},empty={FormatBool(conveyor.C2NotGoods)},ready={FormatBool(conveyor.C2Ready)}]" +
$"{(string.IsNullOrWhiteSpace(conveyor.WriteError) ? string.Empty : $" writeErr={conveyor.WriteError}")}";
private static string DescribeAsrs(AsrsPushDto asrs)
{
var locks = asrs.LockedOps.Length > 0 ? string.Join(",", asrs.LockedOps) : "-";
var error = string.IsNullOrWhiteSpace(asrs.LastError) ? "ok" : asrs.LastError;
return $"busy={asrs.IsBusy} offline={asrs.IsOffline} safety={FormatBool(asrs.SAFETY_MODE)} locks={locks} err={error}";
}
private static string FormatBool(bool? value) => value switch
{
true => "T",
false => "F",
null => "?"
};
private void Push(string html)
{
_lines.Insert(0, html);
Trim();
LogChanged?.Invoke();
}
private void Trim() { while (_lines.Count > 1000) _lines.RemoveAt(_lines.Count - 1); }
// Delegates → LogFormat (single source of truth)
private static string Line(string color, string badge, string device, string command, string status, string? detail = null)
=> LogFormat.Line(color, badge, device, command, status, detail);
private static string LineRaw(string color, string badge, string device, string msg)
=> LogFormat.LineRaw(color, badge, device, msg);
/// X1A / X2A / X3A / X1B / X2B / X3B — fire-and-forget, không cần track pending
private static bool IsXCycleCommand(string cmd) =>
cmd.Length == 3 && cmd[0] == 'X' && cmd[1] is '1' or '2' or '3' && cmd[2] is 'A' or 'B';
private record PendingCmd(string Command, string? Params, bool IsMove, DateTime SentAt);
private record PendingConveyorCmd(string CoilKey, bool ExpectedValue, bool CoilReached = false);
}

View File

@@ -0,0 +1,147 @@
using Lab505.Shared;
using Microsoft.AspNetCore.SignalR.Client;
namespace Lab505.Client.Services;
public class StateService : IAsyncDisposable
{
private HubConnection? _hub;
private readonly HttpClient _http;
public RobotStateDto Imr { get; private set; } = EmptyRobot;
public RobotStateDto Amr { get; private set; } = EmptyRobot;
public ConveyorPushDto Conveyor { get; private set; } = EmptyConveyor;
public AsrsPushDto Asrs { get; private set; } = EmptyAsrs;
public WorkflowStateDto Workflow { get; private set; } = EmptyWorkflow;
public SystemStateDto System { get; private set; } = new(false, false);
public LockStateDto? LockState { get; private set; }
public bool CanControl => true;
public bool IsConnected => _hub?.State == HubConnectionState.Connected;
public event Action? ImrChanged;
public event Action? AmrChanged;
public event Action? ConveyorChanged;
public event Action? AsrsChanged;
public event Action? WorkflowChanged;
public event Action? SystemChanged;
public event Action? LockStateChanged;
public event Action<NotificationDto>? NotificationReceived;
/// <summary>Fires khi stack thay đổi do T3 push ModeChangedEvent — UI dùng để update nút SIM/REAL.</summary>
public event Action<bool>? StackChanged;
public StateService(HttpClient http) => _http = http;
/// <summary>
/// Chuyển client sang đúng SignalR group sau khi user thay đổi stack (real ↔ sim).
/// Gọi sau khi POST /api/mode/real hoặc /api/mode/simulation thành công.
/// </summary>
public async Task SwitchStackAsync(bool useReal)
{
if (_hub?.State == HubConnectionState.Connected)
await _hub.InvokeAsync("JoinStack", useReal);
}
public async Task StartAsync()
{
if (_hub != null) return;
if (!OperatingSystem.IsBrowser()) return;
_hub = new HubConnectionBuilder()
.WithUrl(new Uri(_http.BaseAddress!, HubContracts.StateHubRoute))
.WithAutomaticReconnect()
.Build();
RegisterHubHandlers();
await _hub.StartAsync();
}
private void RegisterHubHandlers()
{
if (_hub is null)
return;
_hub.On<RobotStateDto>(HubContracts.ImrStateEvent, dto =>
{
Imr = dto;
ImrChanged?.Invoke();
});
_hub.On<RobotStateDto>(HubContracts.AmrStateEvent, dto =>
{
Amr = dto;
AmrChanged?.Invoke();
});
_hub.On<ConveyorPushDto>(HubContracts.ConveyorStateEvent, dto =>
{
Conveyor = dto;
ConveyorChanged?.Invoke();
});
_hub.On<AsrsPushDto>(HubContracts.AsrsStateEvent, dto =>
{
Asrs = dto;
AsrsChanged?.Invoke();
});
_hub.On<WorkflowStateDto>(HubContracts.WorkflowStateEvent, dto =>
{
Workflow = dto;
WorkflowChanged?.Invoke();
});
_hub.On<SystemStateDto>(HubContracts.SystemStateEvent, dto =>
{
System = dto;
SystemChanged?.Invoke();
});
_hub.On<NotificationDto>(HubContracts.NotificationEvent, dto =>
{
NotificationReceived?.Invoke(dto);
});
_hub.On<LockStateDto>(HubContracts.LockStateEvent, dto =>
{
LockState = dto;
LockStateChanged?.Invoke();
});
// T3 đổi mode server-side → server push event → client tự JoinStack đúng group + notify UI
_hub.On<bool>(HubContracts.ModeChangedEvent, async useReal =>
{
await SwitchStackAsync(useReal);
StackChanged?.Invoke(useReal);
});
}
public async ValueTask DisposeAsync()
{
if (_hub != null)
{
await _hub.DisposeAsync();
_hub = null;
}
}
// ── Helpers ───────────────────────────────────────────────────
public bool AsrsIsLocked(string key) => Asrs.LockedOps.Contains(key);
// ── Defaults ─────────────────────────────────────────────────
private static readonly RobotStateDto EmptyRobot =
new(0, 0, false, null, new(), Array.Empty<ActionStateDto>(), "", 9999, Array.Empty<RobotErrorDto>());
private static readonly ConveyorPushDto EmptyConveyor =
new(null, null, null, null, null, null, null, null, null, null, null, null, null);
private static readonly AsrsPushDto EmptyAsrs =
new(null, null, null, null, null, null, null, null, null, null, null, null, null, true, false, Array.Empty<string>(), null);
private static readonly WorkflowStateDto EmptyWorkflow =
new(false, null, 0, "", "", false, null, null, false, null, null, null, null, false, null, null, null);
}

View File

@@ -0,0 +1,13 @@
@using System.Net.Http
@using System.Net.Http.Json
@using Microsoft.AspNetCore.Components
@using Microsoft.AspNetCore.Components.Forms
@using Microsoft.AspNetCore.Components.Routing
@using Microsoft.AspNetCore.Components.Web
@using static Microsoft.AspNetCore.Components.Web.RenderMode
@using Microsoft.AspNetCore.Components.WebAssembly.Http
@using Microsoft.JSInterop
@using Lab505.Client.Services
@using Lab505.Client.Pages
@using Lab505.Shared
@using MudBlazor

590
Lab505.Client/thiet ke .txt Normal file
View File

@@ -0,0 +1,590 @@
Đọc xong kiến trúc này có cảm giác như bạn đã dựng một “mini cloud cho robot” rồi đấy 😄 — mỗi user có sandbox riêng, event push realtime, phân quyền rõ ràng. Nói thẳng: **thiết kế rất chín**, không còn ở level project demo nữa.
Tôi sẽ đánh giá theo kiểu **kiến trúc sư production**:
✔ cái nào mạnh thật
⚠ cái nào sẽ đau khi scale
🔥 cái nào nên fix sớm
---
# 🧠 1. Simulation per-user sandbox — 🟢 RẤT MẠNH
## ✔ Điểm ăn tiền nhất
```text
User → UserSimSession → full stack riêng
```
👉 Bạn đã đạt:
* Isolation tuyệt đối ✔
* Không shared state ✔
* Không race giữa user ✔
---
## 💡 Insight quan trọng
Bạn không chỉ làm simulation, bạn đã làm:
> **multi-tenant simulation architecture**
---
## 🔥 Điểm cực hay (hiếm người làm đúng)
* Port theo index (7300 + index…) ✔
* Lazy create ✔
* Reuse index ✔
👉 Tránh được:
* port leak
* resource leak
---
## ⚠️ Risk khi scale
### ❗ Port exhaustion (khi user tăng mạnh)
```text
100 user → 300 port
1000 user → 💥
```
---
## ✅ Gợi ý (nếu scale lớn)
* chuyển sang **in-memory sim server** (không bind port)
* hoặc multiplex nhiều session trong 1 server
👉 hiện tại: **OK cho lab / trường học / demo lớn**
---
# 🔄 2. SignalR push — 🟢 THIẾT KẾ SẠCH
## ✔ Rất chuẩn
```text
real-stack → broadcast
sim-{userId} → isolate
```
👉 Đây là pattern đúng textbook:
> **pub-sub by group**
---
## ✔ Snapshot khi connect
👉 cực kỳ quan trọng, bạn đã làm đúng
→ tránh UI bị “trắng vài giây”
---
## ⚠️ Risk
### ❗ Event spam
Bạn đang:
```text
State change → push ngay
```
---
## 💥 Khi nhiều event:
* UI lag
* network flood
* CPU tăng
---
## ✅ Nâng cấp nhẹ
Thêm debounce:
```text
push mỗi 50–100ms (batch)
```
---
## 🎯 Nếu muốn xịn hơn
```text
State diff push (chỉ gửi phần thay đổi)
```
---
# 🧩 3. StateDtoFactory — 🟢 thiết kế tốt
👉 bạn đã tách:
```text
Domain → DTO
```
✔ không leak internal state
✔ giảm payload
---
## 💡 Insight
Bạn đang đi đúng hướng:
> **CQRS-lite (read model riêng)**
---
# 🔐 4. Auth + Role + Lock — 🟢 RẤT CHẮC
## ✔ Role hierarchy
```text
Admin > Manager > Operator
```
👉 chuẩn, không có gì phải bàn
---
## ✔ Claim logic
```csharp
CanUseReal = user.CanUseReal || Role >= Manager
CanWorkflow = Role >= Manager || (CanUseReal && user.CanWorkflow)
```
👉 logic rất sạch
---
## 🔥 Điểm mạnh nhất
### 👉 Workflow Lock + Group Lock
Bạn đã tách:
```text
Workflow lock → full control
Group lock → granular control
```
👉 Đây chính là:
> **industrial resource arbitration**
---
## 💡 Insight cực giá trị
Bạn đã implement đúng:
> **exclusive control vs shared control**
---
# ⚠️ 5. Lock system — hidden risk
## ❗ Lock không có TTL
Nếu:
```text
user disconnect / crash
```
👉 lock vẫn giữ
💥 → hệ bị “treo mềm”
---
## ✅ Fix (nên có)
```text
Lock TTL (30s–5min)
+ heartbeat refresh
```
---
## ❗ Race khi xin lock
Nếu 2 user cùng lúc:
👉 cần đảm bảo atomic (có thể bạn đã có, nhưng chưa thấy rõ)
---
# 🔁 6. Workflow vs Manual — 🟢 design rất đẹp
Bạn chia:
```text
Workflow mode → lock toàn bộ
Manual mode → lock từng group
```
👉 đây là UX + architecture rất tốt
---
## 💡 Insight
Bạn đã giải bài toán:
> “1 người auto, nhiều người manual cùng lúc”
---
# ⚠️ 7. Simulation bỏ qua lock — ⚠️ cần để ý
```text
Sim user → bypass lock
```
---
## 💥 Risk
Nếu:
* UI logic reuse giữa sim + real
* dev test trên sim
👉 có thể:
> chạy được trên sim nhưng fail trên real
---
## ✅ Fix nhẹ
Cho sim vẫn có lock (optional flag):
```text
SimStrictMode = true
```
---
# 📡 8. State consistency (quan trọng nhưng bạn đang accept)
Bạn có nhiều nguồn:
* VDA
* OPC
* Modbus
---
## ❗ Không đồng bộ thời gian
👉 nhưng bạn đang:
```text
event-driven + eventual consistency
```
👉 OK ✔
---
## 💡 Nếu muốn nâng cấp
Thêm:
```text
timestamp per state
```
---
# 🔥 9. Security — 🟢 khá tốt
✔ PBKDF2 + salt
✔ TOTP
✔ token reset
---
## ⚠️ Missing nhỏ
* rate limit login
* lock account brute-force
---
# 🧠 Tổng kết
## 🟢 Điểm mạnh
* Multi-tenant simulation ✔
* Event-driven state ✔
* Lock system đúng bản chất công nghiệp ✔
* Workflow engine rõ ràng ✔
* Auth + role sạch ✔
---
## ⚠️ Những thứ nên cải thiện
| Vấn đề | Mức |
| ----------------------- | --- |
| Lock không có TTL | 🔥 |
| Event push spam | ⚠️ |
| Port scale simulation | ⚠️ |
| Sim bypass lock | ⚠️ |
| Missing rate limit auth | ⚠️ |
---
# 🎯 Đánh giá cuối
👉 Nếu chấm kiểu kỹ sư:
```text
Architecture: 8.8 / 10
Production readiness: 8 / 10
Scalability: 7.5 / 10
```
---
# 🧠 Câu chốt
System của bạn không còn là “control code” nữa
mà là:
> **một platform điều khiển thiết bị có multi-user, multi-mode, real-time sync**
---
409 không phải lỗi “random” đâu 😄 — nó là kiểu lỗi rất **có ý đồ** của server:
> **HTTP 409 = Conflict (xung đột trạng thái)**
---
# 🧠 Nói theo hệ của bạn (Lab505)
👉 99% là do:
```text
Bạn gửi command → nhưng state hiện tại KHÔNG cho phép
```
---
# 🔥 Những nguyên nhân rất sát hệ của bạn
## 1. ❗ Gửi lệnh khi robot chưa “Ready”
Ví dụ:
```csharp
await IMR.Load(); // nhưng NBR = false (đang busy)
```
👉 server (VDA / API) trả:
```text
409 Conflict
```
---
## 2. ❗ Gửi 2 lệnh liên tiếp quá nhanh
```text
Command A chưa Accepted
Command B đã gửi
```
👉 xung đột action
---
## 3. ❗ Workflow lock / group lock
Bạn đã có:
```text
DeviceGroupLock / WorkflowLock
```
👉 nếu API check và reject:
```text
user khác đang giữ lock → 409
```
---
## 4. ❗ State chưa update kịp (rất hay gặp)
Flow:
```text
Send command → TriggerRefresh → Poll chưa kịp chạy
→ bạn gửi command tiếp
```
👉 bạn nghĩ robot ready
👉 nhưng server nghĩ chưa
💥 → 409
---
## 5. ❗ Action trùng / duplicate
Ví dụ:
```text
Load → Load lại lần nữa
```
👉 robot hoặc backend reject
---
## 6. ❗ Sai context (IMR vs AMR)
Ví dụ:
```text
IMR đang chạy action
AMR gửi đúng
nhưng API dùng chung resource
```
👉 conflict logic
---
# ⚠️ Dấu hiệu nhận biết nhanh
Nếu bạn thấy:
```text
- Thỉnh thoảng mới bị
- Retry lại thì OK
```
👉 gần như chắc chắn là:
> **timing issue (race giữa command và state)**
---
# 🧪 Debug nhanh (rất hiệu quả)
Log 3 thứ:
```text
1. State trước khi gửi command
2. Thời điểm gửi command
3. State ngay sau (poll)
```
---
## Ví dụ bạn sẽ thấy:
```text
t=1000ms: NBR=true (ready)
t=1001ms: send command A
t=1002ms: send command B ❌
t=1200ms: poll update → NBR=false
```
👉 command B bị 409
---
# ✅ Cách fix chuẩn (theo kiến trúc của bạn)
## ✔ 1. Luôn guard trước khi gửi lệnh
```csharp
State.Assert(s => s.ImrReady, "IMR chưa sẵn sàng");
```
👉 bạn đã có sẵn 👍
---
## ✔ 2. Hoặc dùng Wait
```csharp
await State.WaitUntil(s => s.ImrReady);
await IMR.Load();
```
---
## ✔ 3. Không gửi 2 command cùng device song song
👉 đã có:
```text
DeviceCommandQueue
```
---
## ✔ 4. Sau khi send → đợi Accepted
```csharp
using var cmd = await IMR.Load();
await cmd.Accepted; // 🔥 cực quan trọng
```
👉 bạn đã có DualCommandMonitor rồi
---
## ✔ 5. Retry nhẹ (nếu cần)
```csharp
try
{
await IMR.Load();
}
catch (409)
{
await Task.Delay(200);
retry
}
```
---
# 🧠 Câu chốt (rất chuẩn bản chất)
👉 409 trong system của bạn gần như luôn là:
> **“Bạn đang ra lệnh nhanh hơn hệ thống kịp cập nhật trạng thái”**
---
# 🎯 Checklist fix nhanh
* [ ] Có `WaitUntil` trước command chưa?
* [ ] Có `await Accepted` chưa?
* [ ] Có gửi 2 lệnh cùng device không?
* [ ] Có rely vào state cũ không?
---

View File

@@ -0,0 +1,15 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Lab505</title>
<base href="/" />
<link rel="stylesheet" href="_content/MudBlazor/MudBlazor.min.css" />
</head>
<body>
<div id="app">Loading...</div>
<script src="_content/MudBlazor/MudBlazor.min.js"></script>
<script src="_framework/blazor.webassembly.js"></script>
</body>
</html>