first commit -push

This commit is contained in:
dungtt
2025-10-15 15:15:53 +07:00
parent 674ae395be
commit a9577c5756
885 changed files with 74595 additions and 0 deletions

View File

@@ -0,0 +1,216 @@
@using RobotNet.Shares
@using RobotNet.Clients
@using RobotNet.WebApp.Scripts.Models
@inject ISnackbar Snackbar
@inject IHttpClientFactory httpFactory
<MudDialog>
<TitleContent>
<MudText Typo="Typo.h6">
@Title
</MudText>
</TitleContent>
<DialogContent>
<div class="d-flex flex-column" style="width: 500px;">
@foreach (var param in Model.Parameters)
{
<div class="d-flex align-items-center mb-2">
<div class="d-flex flex-row-reverse me-2" style="width: 200px;">
<MudText>@param.Name : </MudText>
</div>
<div style="flex: 1;">
@switch (param.Type)
{
case "System.Boolean":
<MudSwitch T="bool" Color="Color.Primary" @bind-Value="@param.BoolValue" />
break;
case "System.Byte":
<MudNumericField T="byte"
@bind-Value="@param.ByteValue"
Min="@System.Byte.MinValue"
Max="@System.Byte.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.SByte":
<MudNumericField T="sbyte"
@bind-Value="@param.SByteValue"
Min="@System.SByte.MinValue"
Max="@System.SByte.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Int16":
<MudNumericField T="short"
@bind-Value="@param.ShortValue"
Min="@System.Int16.MinValue"
Max="@System.Int16.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.UInt16":
<MudNumericField T="ushort"
@bind-Value="@param.UShortValue"
Min="@System.UInt16.MinValue"
Max="@System.UInt16.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Int32":
<MudNumericField T="int"
@bind-Value="@param.IntValue"
Min="@System.Int32.MinValue"
Max="@System.Int32.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.UInt32":
<MudNumericField T="uint"
@bind-Value="@param.UIntValue"
Min="@System.UInt32.MinValue"
Max="@System.UInt32.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Int64":
<MudNumericField T="long"
@bind-Value="@param.LongValue"
Min="@System.Int64.MinValue"
Max="@System.Int64.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.UInt64":
<MudNumericField T="ulong"
@bind-Value="@param.ULongValue"
Min="@System.UInt64.MinValue"
Max="@System.UInt64.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Single":
<MudNumericField T="float"
@bind-Value="@param.FloatValue"
Min="@System.Single.MinValue"
Max="@System.Single.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Double":
<MudNumericField T="double"
@bind-Value="@param.DoubleValue"
Min="@System.Double.MinValue"
Max="@System.Double.MaxValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Decimal":
<MudNumericField T="decimal"
@bind-Value="@param.DecimalValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.String":
<MudTextField @bind-Value="@param.StringValue"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Char":
<MudTextField @bind-Value="@param.CharValue"
MaxLength="1"
Label="@param.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Threading.CancellationToken":
<span>
&lt;CancellationToken&gt;
</span>
break;
default:
<MudAlert Severity="Severity.Error" Dense>Unsupport parameter with type @param.Type</MudAlert>
break;
}
</div>
</div>
}
</div>
</DialogContent>
<DialogActions>
<MudButton OnClick="OnCancel">Cancel</MudButton>
<MudButton Color="Color.Primary" OnClick="Instantiate" Disabled="@IsInstantiating">Instantiate</MudButton>
</DialogActions>
</MudDialog>
@code {
[CascadingParameter]
private IMudDialogInstance Dialog { get; set; } = null!;
[Parameter, EditorRequired]
public ScriptMissionModel Model { get; set; } = default!;
public string Title => $"Instantiate Mission {Model.Name}";
private HttpClient http = default!;
private bool IsInstantiating = false;
protected override void OnInitialized()
{
base.OnInitialized();
http = httpFactory.CreateClient("ScriptManagerAPI");
}
private void OnCancel() => Dialog.Cancel();
private async Task Instantiate()
{
if (IsInstantiating) return;
IsInstantiating = true;
StateHasChanged(); // Force UI update to reflect instantiation state
var parameters = Model.Parameters
.Where(p => p.Type != "RobotNet.Script.IRobot")
.ToDictionary(p => p.Name, p => p.ToString());
var result = await http.PostFromJsonAsync<MessageResult<Guid>>("api/ScriptMissions/Runner", new InstanceMissionCreateModel(Model.Name, parameters));
if (result is null)
{
Snackbar.Add("Failed to instantiate mission: server response null", Severity.Error);
}
else if (result.IsSuccess)
{
Snackbar.Add($"Mission {Model.Name} instantiated successfully with ID: {result.Data}", Severity.Success);
Dialog.Close(DialogResult.Ok(Model.Name));
}
else
{
Snackbar.Add($"Failed to instantiate mission: {result.Message}", Severity.Error);
}
}
}

View File

@@ -0,0 +1,259 @@
@implements IDisposable
@using Microsoft.AspNetCore.SignalR.Client
@using RobotNet.WebApp.Scripts.Models
@inject IHttpClientFactory httpFactory
@inject IDialogService DialogService
<div class="flex-grow-1 h-100 position-relative overflow-hidden">
<div @ref="divRef" class="w-100 h-100 position-absolute top-0 start-0 overflow-hidden">
<MudTable Style="margin: 10px;" Items="scriptMissions" Height="@TableHeight" FixedHeader Virtualize Hover Elevation="6">
<ToolBarContent>
<div @ref="toolbarRef" class="w-100 d-flex flex-row">
<h3>Danh sách Script Missions</h3>
<MudSpacer />
</div>
</ToolBarContent>
<ColGroup>
<col style="width:60px;" />
<col />
<col />
<col style="width:60px;" />
<col style="width:60px;" />
</ColGroup>
<HeaderContent>
<MudTh>STT</MudTh>
<MudTh>Tên</MudTh>
<MudTh>Parameters</MudTh>
<MudTh>Script</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd>@context.Index</MudTd>
<MudTd DataLabel="Tên">@context.Name</MudTd>
<MudTd DataLabel="Parameters">
<span>
@if (context.Parameters?.Any() == true)
{
<MudIconButton Icon="@Icons.Material.Filled.Info" Color="Color.Primary" Size="Size.Small"
OnClick="@(() => ShowParametersDialog(context))" />
}
else
{
<span>Không có</span>
}
</span>
</MudTd>
<MudTd DataLabel="Script">
<span>
<MudIconButton Icon="@Icons.Material.Filled.Visibility" Color="Color.Primary" Size="Size.Small"
OnClick="@(() => ShowCodeDialog(context.Code))" />
</span>
</MudTd>
<MudTd>
<span>
<MudIconButton Icon="@Icons.Material.Filled.PlayArrow" Color="Color.Success" Size="Size.Small"
Disabled="@CallDisabled" OnClick="@(() => ShowInstantiateMissionDialog(context))" />
</span>
</MudTd>
</RowTemplate>
</MudTable>
</div>
</div>
<MudDialog @bind-Visible="_parametersDialogOpen">
<DialogContent>
<h6>Thông tin Parameters</h6>
@if (_selectedParameters != null)
{
<MudTable Items="_selectedParameters" Style="min-width: 400px;">
<HeaderContent>
<MudTh>Tên</MudTh>
<MudTh>Kiểu</MudTh>
<MudTh>Default</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd>@context.Name</MudTd>
<MudTd>@context.Type</MudTd>
<MudTd>@context.Default</MudTd>
</RowTemplate>
</MudTable>
}
</DialogContent>
<DialogActions>
<MudButton OnClick="CloseParametersDialog">Đóng</MudButton>
</DialogActions>
</MudDialog>
<MudDialog @bind-Visible="_codeDialogOpen" Style="min-width: 900px;">
<DialogContent>
<h6>Mã Script đầy đủ</h6>
<MudPaper Class="pa-2" Style="overflow-x:auto;">
<pre style="white-space:pre-wrap;word-break:break-all;">@_selectedCode</pre>
</MudPaper>
</DialogContent>
<DialogActions>
<MudButton OnClick="CloseCodeDialog">Đóng</MudButton>
</DialogActions>
</MudDialog>
@code {
[CascadingParameter]
private ProcessorHubClient ProcessorHub { get; set; } = null!;
private string TableHeight = "0px";
private ElementReference divRef;
private ElementReference toolbarRef;
private HttpClient http = default!;
private List<ScriptMissionModel> scriptMissions = [];
// Dialog state
private bool _parametersDialogOpen = false;
private IEnumerable<ScriptValueModel>? _selectedParameters;
private bool _codeDialogOpen = false;
private string? _selectedCode;
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (firstRender)
{
var rect = await divRef.MudGetBoundingClientRectAsync();
var toolbarRect = await toolbarRef.MudGetBoundingClientRectAsync();
TableHeight = $"{rect.Height - 25 - Math.Max(toolbarRect.Height, 64)}px";
StateHasChanged();
}
}
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
http = httpFactory.CreateClient("ScriptManagerAPI");
await ReloadData();
if (ProcessorHub.IsConnected)
{
OnProcessorStateChanged(await ProcessorHub.GetState());
}
ProcessorHub.StateChanged += OnProcessorStateChanged;
ProcessorHub.ConnectionStateChanged += OnConnectionStateChanged;
}
private void OnConnectionStateChanged(HubConnectionState state)
{
if (state == HubConnectionState.Connected)
{
_ = InvokeAsync(async Task () =>
{
OnProcessorStateChanged(await ProcessorHub.GetState());
});
}
}
private bool isRebuild = false;
private bool CallDisabled = true;
private void OnProcessorStateChanged(ProcessorState state)
{
if (state == ProcessorState.Building)
{
isRebuild = true;
}
else if (state == ProcessorState.Ready)
{
if (isRebuild)
{
isRebuild = false;
_ = InvokeAsync(async Task () =>
{
await ReloadData();
});
}
}
if (CallDisabled)
{
if (state == ProcessorState.Running)
{
CallDisabled = false;
StateHasChanged();
}
}
else
{
if (state != ProcessorState.Running)
{
CallDisabled = true;
StateHasChanged();
}
}
}
private async Task ReloadData()
{
scriptMissions.Clear();
var missions = await http.GetFromJsonAsync<List<ScriptMissionDto>>("/api/ScriptMissions") ?? [];
foreach (var item in missions.Select((value, index) => (value, index)))
{
scriptMissions.Add(new ScriptMissionModel(item.index + 1, item.value));
}
StateHasChanged();
}
private void ShowParametersDialog(ScriptMissionModel model)
{
_selectedParameters = model.Parameters;
_parametersDialogOpen = true;
StateHasChanged();
}
private void CloseParametersDialog()
{
_parametersDialogOpen = false;
_selectedParameters = null;
StateHasChanged();
}
private void ShowCodeDialog(string code)
{
_selectedCode = code;
_codeDialogOpen = true;
StateHasChanged();
}
private void CloseCodeDialog()
{
_codeDialogOpen = false;
_selectedCode = null;
StateHasChanged();
}
private async Task ShowInstantiateMissionDialog(ScriptMissionModel model)
{
if (CallDisabled) return;
foreach (var parameter in model.Parameters)
{
parameter.Reset();
}
;
var parameters = new DialogParameters<InstantiateMissionDialog>()
{
{x => x.Model, model},
};
var dialog = await DialogService.ShowAsync<InstantiateMissionDialog>("Instantiate new mission", parameters);
var resultDialog = await dialog.Result;
}
public void Dispose()
{
ProcessorHub.StateChanged -= OnProcessorStateChanged;
ProcessorHub.ConnectionStateChanged -= OnConnectionStateChanged;
}
}

View File

@@ -0,0 +1,127 @@
@using Microsoft.AspNetCore.SignalR.Client
@using Microsoft.CodeAnalysis
@implements IDisposable
@inject ISnackbar Snackbar
@inject IDialogService DialogService
<div class="w-100">
<MudCard Class="m-2" Style="height: 300px" Elevation="6">
<MudCardHeader>
<CardHeaderContent>
<MudText Typo="Typo.h6">Process Controller - @State</MudText>
</CardHeaderContent>
<CardHeaderActions>
<ActionButton Icon="mdi-receipt-text-remove" Large Tooltip="Clear console" OnClick="ClearConsole" />
<ActionButton Icon="mdi-refresh text-primary" Large Tooltip="Reset" Disabled="@ResetDisable" OnClick="Reset" />
<ActionButton Icon="mdi-cog-play text-primary" Large Tooltip="Build" Disabled="@BuildDisable" OnClick="Build" />
<ActionButton Icon="mdi-play text-success" Large Tooltip="Run" Disabled="@RunDisable" OnClick="Run" />
<ActionButton Icon="mdi-stop text-danger" Large Tooltip="Stop" Disabled="@StopDisable" OnClick="Stop" />
</CardHeaderActions>
</MudCardHeader>
<MudCardContent>
<ProcessorConsole @ref="processorConsole" />
</MudCardContent>
</MudCard>
</div>
@code {
[CascadingParameter]
private ProcessorHubClient ProcessorHub { get; set; } = null!;
private ProcessorConsole? processorConsole;
public ProcessorState State { get; private set; } = ProcessorState.Idle;
private ProcessorRequest Request = ProcessorRequest.None;
private bool ResetDisable => State != ProcessorState.Idle && State != ProcessorState.Ready && State != ProcessorState.Error && State != ProcessorState.BuildError;
private bool BuildDisable => State != ProcessorState.Idle && State != ProcessorState.Ready && State != ProcessorState.Error && State != ProcessorState.BuildError;
private bool RunDisable => State != ProcessorState.Ready;
private bool StopDisable => State != ProcessorState.Running;
protected override async Task OnInitializedAsync()
{
if (ProcessorHub.IsConnected)
{
OnProcessorStateChanged(await ProcessorHub.GetState());
}
ProcessorHub.StateChanged += OnProcessorStateChanged;
ProcessorHub.RequestChanged += OnRequestChanged;
ProcessorHub.ConnectionStateChanged += OnConnectionStateChanged;
await base.OnInitializedAsync();
}
private void OnConnectionStateChanged(HubConnectionState state)
{
if (state == HubConnectionState.Connected)
{
_ = InvokeAsync(async Task () =>
{
OnProcessorStateChanged(await ProcessorHub.GetState());
});
}
}
private void OnProcessorStateChanged(ProcessorState state)
{
if (State == state) return;
State = state;
StateHasChanged();
}
private void OnRequestChanged(ProcessorRequest request)
{
Request = request;
StateHasChanged();
}
private async Task Reset()
{
var result = await ProcessorHub.Reset();
if (!result.IsSuccess)
{
Snackbar.Add($"Failed to reset processor: {result.Message}", Severity.Error);
}
}
private async Task Build()
{
var result = await ProcessorHub.Build();
if (!result.IsSuccess)
{
Snackbar.Add($"Failed to build processor: {result.Message}", Severity.Error);
}
}
private async Task Run()
{
var result = await ProcessorHub.Run();
if (!result.IsSuccess)
{
Snackbar.Add($"Failed to run processor: {result.Message}", Severity.Error);
}
}
private async Task Stop()
{
var result = await ProcessorHub.Stop();
if (!result.IsSuccess)
{
Snackbar.Add($"Failed to stop processor: {result.Message}", Severity.Error);
}
}
private void ClearConsole()
{
processorConsole?.Clear();
}
public void Dispose()
{
ProcessorHub.StateChanged -= OnProcessorStateChanged;
ProcessorHub.RequestChanged -= OnRequestChanged;
ProcessorHub.ConnectionStateChanged -= OnConnectionStateChanged;
}
}

View File

@@ -0,0 +1,253 @@
@using RobotNet.Shares
@using RobotNet.Clients
@using RobotNet.WebApp.Scripts.Models
@inject ISnackbar Snackbar
@inject IHttpClientFactory httpFactory
<MudDialog>
<TitleContent>
<MudText Typo="Typo.h6">
@Title
</MudText>
</TitleContent>
<DialogContent>
<div class="d-flex flex-column" style="width: 500px;">
<div class="d-flex align-items-center mb-2">
<div class="d-flex flex-row-reverse me-2" style="width: 200px;">
<MudText>@Model.Name : </MudText>
</div>
<div style="flex: 1;">
@switch (Model.TypeName)
{
case "System.Boolean":
<MudSwitch T="bool" Color="Color.Primary" @bind-Value="@ValueModel.BoolValue" />
break;
case "System.Byte":
<MudNumericField T="byte"
@bind-Value="@ValueModel.ByteValue"
Min="@System.Byte.MinValue"
Max="@System.Byte.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.SByte":
<MudNumericField T="sbyte"
@bind-Value="@ValueModel.SByteValue"
Min="@System.SByte.MinValue"
Max="@System.SByte.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Int16":
<MudNumericField T="short"
@bind-Value="@ValueModel.ShortValue"
Min="@System.Int16.MinValue"
Max="@System.Int16.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.UInt16":
<MudNumericField T="ushort"
@bind-Value="@ValueModel.UShortValue"
Min="@System.UInt16.MinValue"
Max="@System.UInt16.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Int32":
<MudNumericField T="int"
@bind-Value="@ValueModel.IntValue"
Min="@System.Int32.MinValue"
Max="@System.Int32.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.UInt32":
<MudNumericField T="uint"
@bind-Value="@ValueModel.UIntValue"
Min="@System.UInt32.MinValue"
Max="@System.UInt32.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Int64":
<MudNumericField T="long"
@bind-Value="@ValueModel.LongValue"
Min="@System.Int64.MinValue"
Max="@System.Int64.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.UInt64":
<MudNumericField T="ulong"
@bind-Value="@ValueModel.ULongValue"
Min="@System.UInt64.MinValue"
Max="@System.UInt64.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Single":
<MudNumericField T="float"
@bind-Value="@ValueModel.FloatValue"
Min="@System.Single.MinValue"
Max="@System.Single.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Double":
<MudNumericField T="double"
@bind-Value="@ValueModel.DoubleValue"
Min="@System.Double.MinValue"
Max="@System.Double.MaxValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Decimal":
<MudNumericField T="decimal"
@bind-Value="@ValueModel.DecimalValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.String":
<MudTextField @bind-Value="@ValueModel.StringValue"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Char":
<MudTextField @bind-Value="@ValueModel.CharValue"
MaxLength="1"
Label="@ValueModel.Type"
ShrinkLabel="true"
Variant="Variant.Outlined"
Margin="Margin.Dense" />
break;
case "System.Threading.CancellationToken":
<span>
&lt;CancellationToken&gt;
</span>
break;
default:
<MudAlert Severity="Severity.Error" Dense>Unsupport parameter with type @ValueModel.Type</MudAlert>
break;
}
</div>
</div>
</div>
</DialogContent>
<DialogActions>
<MudButton OnClick="OnCancel">Cancel</MudButton>
<MudButton Color="Color.Primary" OnClick="RequestSetValue" Disabled="@IsRequesing">Update</MudButton>
</DialogActions>
</MudDialog>
@code {
[CascadingParameter]
private IMudDialogInstance Dialog { get; set; } = null!;
[Parameter, EditorRequired]
public ScriptVariableModel Model { get; set; } = default!;
public string Title => $"Set Variable \"{Model.Name}\"";
private HttpClient http = default!;
private ScriptValueModel ValueModel = null!;
private bool IsRequesing = false;
protected override void OnInitialized()
{
base.OnInitialized();
ValueModel = new ScriptValueModel(Model.Name, Model.TypeName, "");
switch (Model.TypeName)
{
case "System.Boolean":
ValueModel.BoolValue = default;
break;
case "System.Byte":
ValueModel.ByteValue = default;
break;
case "System.SByte":
ValueModel.SByteValue = default;
break;
case "System.Int16":
ValueModel.ShortValue = default;
break;
case "System.UInt16":
ValueModel.UShortValue = default;
break;
case "System.Int32":
ValueModel.IntValue = default;
break;
case "System.UInt32":
ValueModel.UIntValue = default;
break;
case "System.Int64":
ValueModel.LongValue = default;
break;
case "System.UInt64":
ValueModel.ULongValue = default;
break;
case "System.Single":
ValueModel.FloatValue = default;
break;
case "System.Double":
ValueModel.DoubleValue = default;
break;
case "System.Decimal":
ValueModel.DecimalValue = default;
break;
}
http = httpFactory.CreateClient("ScriptManagerAPI");
}
private async Task RequestSetValue()
{
if (IsRequesing) return;
IsRequesing = true;
StateHasChanged(); // Force UI update to reflect instantiation state
var result = await http.PutFromJsonAsync<MessageResult>($"/api/ScriptVariables/{ValueModel.Name}", new UpdateVariableModel(ValueModel.Name, ValueModel.ToString()));
if (result == null)
{
Snackbar.Add("Failed to instantiate mission: server response null", Severity.Error);
}
else if (result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Success);
Dialog.Close();
}
else
{
Snackbar.Add($"Failed to reset variable value: {result.Message}", Severity.Error);
Dialog.Close();
}
}
private void OnCancel() => Dialog.Cancel();
}

View File

@@ -0,0 +1,263 @@
@implements IAsyncDisposable
@using Microsoft.AspNetCore.SignalR.Client
@using RobotNet.WebApp.Scripts.Models
@inject IHttpClientFactory httpFactory
@inject ScriptTaskHubClient ScriptTaskHub
@inject ISnackbar Snackbar
<div class="flex-grow-1 h-100 position-relative overflow-hidden">
<div @ref="divRef" class="w-100 h-100 position-absolute top-0 start-0 overflow-hidden">
<MudTable Style="margin: 10px;" Items="scriptTasks" Height="@TableHeight" FixedHeader Virtualize Hover Elevation="6">
<ToolBarContent>
<div @ref="toolbarRef" class="w-100 d-flex flex-row">
<h3>Danh sách Script Tasks</h3>
<MudSpacer />
</div>
</ToolBarContent>
<ColGroup>
<col style="width:60px;" />
<col />
<col />
<col style="width:60px;" />
<col style="width:60px;" />
</ColGroup>
<HeaderContent>
<MudTh></MudTh>
<MudTh>Tên</MudTh>
<MudTh>Khoảng thời gian (ms)</MudTh>
<MudTh>Enable</MudTh>
<MudTh>Script</MudTh>
</HeaderContent>
<RowTemplate>
<MudTd>@context.Index</MudTd>
<MudTd DataLabel="Tên">@context.Name</MudTd>
<MudTd DataLabel="Khoảng thời gian">@context.Interval</MudTd>
<MudTd DataLabel="Enable">
<MudSwitch T="bool" @bind-Value="context.Enable" @bind-Value:after="@(() => RequestTaskAction(context.Name, context.Enable))" Color="Color.Primary" Disabled="@actionDisable" />
</MudTd>
<MudTd DataLabel="Script">
<MudIconButton Icon="@Icons.Material.Filled.Visibility" Color="Color.Primary" Size="Size.Small"
OnClick="@(() => ShowCodeDialog(context.Code))" />
</MudTd>
</RowTemplate>
</MudTable>
</div>
</div>
<MudDialog @bind-Visible="_codeDialogOpen" Style="min-width: 900px;">
<DialogContent>
<h6>Mã Script đầy đủ</h6>
<MudPaper Class="pa-2" Style="overflow-x:auto;">
<pre style="white-space:pre-wrap;word-break:break-all;">@_selectedCode</pre>
</MudPaper>
</DialogContent>
<DialogActions>
<MudButton OnClick="CloseCodeDialog">Đóng</MudButton>
</DialogActions>
</MudDialog>
@code {
[CascadingParameter]
private ProcessorHubClient ProcessorHub { get; set; } = null!;
private string TableHeight = "0px";
private ElementReference divRef;
private ElementReference toolbarRef;
private HttpClient http = default!;
private List<ScriptTaskModel> scriptTasks = [];
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (firstRender)
{
var rect = await divRef.MudGetBoundingClientRectAsync();
var toolbarRect = await toolbarRef.MudGetBoundingClientRectAsync();
TableHeight = $"{rect.Height - 25 - Math.Max(toolbarRect.Height, 64)}px";
StateHasChanged();
}
}
// Dialog state
private bool _codeDialogOpen = false;
private string? _selectedCode;
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
http = httpFactory.CreateClient("ScriptManagerAPI");
await ReloadData();
if (ProcessorHub.IsConnected)
{
OnProcessorStateChanged(await ProcessorHub.GetState());
}
ProcessorHub.StateChanged += OnProcessorStateChanged;
ProcessorHub.ConnectionStateChanged += OnConnectionStateChanged;
ScriptTaskHub.TaskResumed += OnTaskResumed;
ScriptTaskHub.TaskPaused += OnTaskPaused;
await ScriptTaskHub.StartAsync();
}
private void OnConnectionStateChanged(HubConnectionState state)
{
if (state == HubConnectionState.Connected)
{
_ = InvokeAsync(async Task () =>
{
OnProcessorStateChanged(await ProcessorHub.GetState());
});
}
}
private bool isRebuild = false;
private bool actionDisable = true;
private void OnProcessorStateChanged(ProcessorState state)
{
if (state == ProcessorState.Building)
{
isRebuild = true;
}
else if (state == ProcessorState.Ready)
{
if (isRebuild)
{
isRebuild = false;
_ = InvokeAsync(async Task () =>
{
await ReloadData();
});
}
}
if (actionDisable)
{
if (state == ProcessorState.Running)
{
actionDisable = false;
StateHasChanged();
}
}
else
{
if (state != ProcessorState.Running)
{
actionDisable = true;
StateHasChanged();
}
}
if (state == ProcessorState.Running)
{
_ = InvokeAsync(async Task () =>
{
var states = await ScriptTaskHub.GetTaskStates();
foreach (var task in scriptTasks)
{
task.Enable = states.ContainsKey(task.Name) && states[task.Name];
}
StateHasChanged();
});
}
}
private async Task ReloadData()
{
await InvokeAsync(async Task () =>
{
scriptTasks.Clear();
var tasks = await http.GetFromJsonAsync<List<ScriptTaskDto>>("/api/ScriptTasks") ?? [];
foreach (var item in tasks.Select((value, index) => (value, index)))
{
scriptTasks.Add(new ScriptTaskModel(item.index + 1, item.value));
}
if (!actionDisable)
{
var states = await ScriptTaskHub.GetTaskStates();
foreach (var task in scriptTasks)
{
task.Enable = states.ContainsKey(task.Name) && states[task.Name];
}
}
StateHasChanged();
});
}
private void ShowCodeDialog(string code)
{
_selectedCode = code;
_codeDialogOpen = true;
}
private void CloseCodeDialog()
{
_codeDialogOpen = false;
_selectedCode = null;
}
private void OnTaskResumed(string taskName)
{
foreach (var task in scriptTasks)
{
if (task.Name == taskName)
{
task.Enable = true;
StateHasChanged();
break;
}
}
}
private void OnTaskPaused(string taskName)
{
foreach (var task in scriptTasks)
{
if (task.Name == taskName)
{
task.Enable = false;
StateHasChanged();
break;
}
}
}
private async Task RequestTaskAction(string name, bool enable)
{
if (actionDisable) return;
if (enable)
{
var result = await ScriptTaskHub.Resume(name);
if (!result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Error);
OnTaskPaused(name);
}
}
else
{
var result = await ScriptTaskHub.Pause(name);
if (!result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Error);
OnTaskResumed(name);
}
}
}
public async ValueTask DisposeAsync()
{
ProcessorHub.StateChanged -= OnProcessorStateChanged;
ProcessorHub.ConnectionStateChanged -= OnConnectionStateChanged;
ScriptTaskHub.TaskResumed -= OnTaskResumed;
ScriptTaskHub.TaskPaused -= OnTaskPaused;
await ScriptTaskHub.StartAsync();
}
}

View File

@@ -0,0 +1,185 @@
@implements IDisposable
@using Microsoft.AspNetCore.SignalR.Client
@using RobotNet.Clients
@using RobotNet.Shares
@inject IHttpClientFactory httpFactory
@inject ISnackbar Snackbar
@inject IDialogService DialogService
<div class="flex-grow-1 h-100 position-relative overflow-hidden">
<div @ref="divRef" class="w-100 h-100 position-absolute top-0 start-0 overflow-hidden">
<MudTable Style="margin: 10px;" Items="_items" Height="@TableHeight" FixedHeader Virtualize Hover Elevation="6">
<ToolBarContent>
<div @ref="toolbarRef" class="w-100 d-flex flex-row">
<h3>Global Variables</h3>
<MudSpacer />
<ActionButton Icon="mdi-refresh text-primary" Large Tooltip="Reset" OnClick="ReloadData" />
</div>
</ToolBarContent>
<ColGroup>
<col style="width:60px;" />
<col />
<col />
<col />
<col style="width:90px;" />
</ColGroup>
<HeaderContent>
<MudTh></MudTh>
<MudTh>Name</MudTh>
<MudTh>Type</MudTh>
<MudTh>Value</MudTh>
<MudTh></MudTh>
</HeaderContent>
<RowTemplate>
<MudTd>@context.Index</MudTd>
<MudTd DataLabel="Name">@context.Name</MudTd>
<MudTd DataLabel="Type">@context.TypeName</MudTd>
<MudTd DataLabel="Value">@context.Value</MudTd>
<MudTd>
<span>
<MudIconButton Icon="@Icons.Material.Filled.Edit" Color="Color.Primary" Size="Size.Small"
Disabled="@CallDisabled" OnClick="@(() => ShowSetValueDialog(context))" />
</span>
<span>
<MudIconButton Icon="@Icons.Material.Filled.Refresh" Color="Color.Secondary" Size="Size.Small"
Disabled="@CallDisabled" OnClick="@(() => ResetValue(context))" />
</span>
</MudTd>
</RowTemplate>
</MudTable>
</div>
</div>
@code {
[CascadingParameter]
private ProcessorHubClient ProcessorHub { get; set; } = null!;
private string TableHeight = "0px";
private ElementReference divRef;
private ElementReference toolbarRef;
private HttpClient http = default!;
private List<ScriptVariableModel> _items = [];
protected override async Task OnAfterRenderAsync(bool firstRender)
{
await base.OnAfterRenderAsync(firstRender);
if (firstRender)
{
var rect = await divRef.MudGetBoundingClientRectAsync();
var toolbarRect = await toolbarRef.MudGetBoundingClientRectAsync();
TableHeight = $"{rect.Height - 25 - Math.Max(toolbarRect.Height, 64)}px";
StateHasChanged();
}
}
protected override async Task OnInitializedAsync()
{
await base.OnInitializedAsync();
http = httpFactory.CreateClient("ScriptManagerAPI");
await ReloadData();
if (ProcessorHub.IsConnected)
{
OnProcessorStateChanged(await ProcessorHub.GetState());
}
ProcessorHub.StateChanged += OnProcessorStateChanged;
ProcessorHub.ConnectionStateChanged += OnConnectionStateChanged;
}
private void OnConnectionStateChanged(HubConnectionState state)
{
if (state == HubConnectionState.Connected)
{
_ = InvokeAsync(async Task () =>
{
OnProcessorStateChanged(await ProcessorHub.GetState());
});
}
}
private bool CallDisabled = true;
private void OnProcessorStateChanged(ProcessorState state)
{
if (state == ProcessorState.Ready)
{
_ = InvokeAsync(async Task () =>
{
await ReloadData();
});
}
if (CallDisabled)
{
if (state == ProcessorState.Running)
{
CallDisabled = false;
StateHasChanged();
}
}
else
{
if (state != ProcessorState.Running)
{
CallDisabled = true;
StateHasChanged();
}
}
}
private async Task ReloadData()
{
_items.Clear();
var vars = await http.GetFromJsonAsync<IEnumerable<ScriptVariableDto>>("/api/ScriptVariables") ?? [];
foreach (var item in vars.Select((value, index) => (value, index)))
{
_items.Add(new ScriptVariableModel(item.index + 1, item.value));
}
StateHasChanged();
}
private async Task ResetValue(ScriptVariableModel model)
{
if (CallDisabled) return;
var result = await http.PutFromJsonAsync<MessageResult>($"/api/ScriptVariables/{model.Name}/Reset", new UpdateVariableModel(model.Name, ""));
if(result == null)
{
Snackbar.Add("Failed to reset variable value: server response null", Severity.Error);
}
else if (result.IsSuccess)
{
Snackbar.Add(result.Message, Severity.Success);
}
else
{
Snackbar.Add($"Failed to reset variable value: {result.Message}", Severity.Error);
}
}
private async Task ShowSetValueDialog(ScriptVariableModel model)
{
if (CallDisabled) return;
var parameters = new DialogParameters<SetVariableValueDialog>()
{
{x => x.Model, model},
};
var dialog = await DialogService.ShowAsync<SetVariableValueDialog>("Set Variable Value", parameters);
var resultDialog = await dialog.Result;
}
public void Dispose()
{
ProcessorHub.StateChanged -= OnProcessorStateChanged;
ProcessorHub.ConnectionStateChanged -= OnConnectionStateChanged;
}
}