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,75 @@
using Lab505.Script.Facades;
using Lab505.Shared;
namespace Lab505.Script;
/// <summary>Script facade for AMR — maps named positions to driver calls.</summary>
public class AmrFacade : IAmrFacade
{
private readonly IAmrRaw _drv;
// Timeout khớp với FlowService — script tuần tự chờ action/NBR trước khi trả về.
private const int ACTION_TIMEOUT_MS = 20 * 60 * 1000;
private const int POS_TIMEOUT_MS = 30 * 60 * 1000;
private static readonly Dictionary<string, (string vda, double x, double y)> _pos =
new(StringComparer.OrdinalIgnoreCase)
{
["Cap1"] = ("Cap1", RobotPositions.AMR_CAP1_X, RobotPositions.AMR_CAP1_Y),
["Cap2"] = ("Cap2", RobotPositions.AMR_CAP2_X, RobotPositions.AMR_CAP2_Y),
};
public AmrFacade(IAmrRaw drv) => _drv = drv;
public async Task GoTo(string position, CancellationToken ct = default)
{
if (!_pos.TryGetValue(position, out var p))
throw new ArgumentException($"AMR: unknown position '{position}'. Valid: {string.Join(", ", _pos.Keys)}");
await _drv.DockToStation(p.vda, ct);
await _drv.WaitMoveTo(POS_TIMEOUT_MS, ct);
}
public async Task Undock(CancellationToken ct = default)
{
var id = await _drv.UndockFromStation_AMR(ct);
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
}
public async Task Load(CancellationToken ct = default)
{
var id = await _drv.Load_Vda(ct);
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
}
public async Task Unload(CancellationToken ct = default)
{
var id = await _drv.Unload_Vda(ct);
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
}
public async Task Pause(CancellationToken ct = default)
{
var id = await _drv.StartPause(ct);
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
}
public async Task Resume(CancellationToken ct = default)
{
var id = await _drv.StopPause(ct);
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
}
public async Task InitPosition(double x, double y, double theta, CancellationToken ct = default)
{
var id = await _drv.InitPosition(x, y, theta, ct);
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
}
public Task Cancel(CancellationToken ct = default) => _drv.Cancel_Vda(ct);
public bool IsAt(string position, double tol = 0.2)
{
if (!_pos.TryGetValue(position, out var p)) return false;
return _drv.IsAtPosition(p.x, p.y, tol);
}
}

View File

@@ -0,0 +1,24 @@
using Lab505.Script.Facades;
namespace Lab505.Script;
/// <summary>Script facade for Dobot — Pickup delegates to IMR VDA.</summary>
public class DobotFacade : IDobotFacade
{
private readonly IDobotRaw _dobot;
private readonly IImrRaw _imr;
public DobotFacade(IDobotRaw dobot, IImrRaw imr)
{
_dobot = dobot;
_imr = imr;
}
public Task PowerOn(CancellationToken t = default) => _dobot.PowerOn(t);
public Task GoHome(CancellationToken t = default) => _dobot.GoHome(t);
public Task Continue(CancellationToken t = default) => _dobot.Continue(t);
public Task Cancel(CancellationToken t = default) => _dobot.Cancel(t);
public Task Pickup(int ok, int ng, CancellationToken t = default)
=> _imr.PickUp_Vda(ok, ng, t);
}

View File

@@ -0,0 +1,32 @@
namespace Lab505.Script.Facades;
/// <summary>Script facade for the AMR robot — use named positions instead of raw coordinates.</summary>
public interface IAmrFacade
{
/// <summary>Move to named position. Positions: "Cap1", "Cap2"</summary>
Task GoTo(string position, CancellationToken ct = default);
/// <summary>Undock from current docked station</summary>
Task Undock(CancellationToken ct = default);
/// <summary>Load items onto the robot via VDA</summary>
Task Load(CancellationToken ct = default);
/// <summary>Unload items from the robot via VDA</summary>
Task Unload(CancellationToken ct = default);
/// <summary>Pause the robot's current task (VDA startPause)</summary>
Task Pause(CancellationToken ct = default);
/// <summary>Resume a paused task (VDA stopPause)</summary>
Task Resume(CancellationToken ct = default);
/// <summary>Re-initialize the robot's pose (x, y in metres, theta in radians)</summary>
Task InitPosition(double x, double y, double theta, CancellationToken ct = default);
/// <summary>Cancel current task</summary>
Task Cancel(CancellationToken ct = default);
/// <summary>Check if robot is currently at named position</summary>
bool IsAt(string position, double tol = 0.2);
}

View File

@@ -0,0 +1,21 @@
namespace Lab505.Script.Facades;
/// <summary>Subset of AmrVdaDriver methods needed by AmrFacade — breaks circular dependency.</summary>
public interface IAmrRaw
{
Task DockToStation(string target, CancellationToken t = default);
Task<string> UndockFromStation_AMR(CancellationToken t = default);
Task<string> Load_Vda(CancellationToken t = default);
Task<string> Unload_Vda(CancellationToken t = default);
Task<string> StartPause(CancellationToken t = default);
Task<string> StopPause(CancellationToken t = default);
Task<string> InitPosition(double x, double y, double theta, CancellationToken t = default);
Task Cancel_Vda(CancellationToken t = default);
bool IsAtPosition(double tx, double ty, double tol = 0.2);
/// <summary>Chờ action có ActionID cụ thể đạt FINISHED. Throw nếu FAILED/ABORTED hoặc timeout.</summary>
Task WaitActionIdCompleted(string actionId, int timeoutMs, CancellationToken ct = default);
/// <summary>Chờ MoveTo hoàn thành — dựa vào NBR false→true.</summary>
Task WaitMoveTo(int timeoutMs, CancellationToken ct = default);
}

View File

@@ -0,0 +1,25 @@
namespace Lab505.Script.Facades;
/// <summary>Script-friendly ASRS interface — no dependency on ASRSState class.</summary>
public interface IAsrsFacade
{
bool IsBusy { get; }
bool IsLocked(string key);
event Action? OnOperationStateChanged;
Task SYSTEM_HOMING(CancellationToken token = default);
Task X1_S12(CancellationToken token = default);
Task X2_S12(CancellationToken token = default);
Task X3_S12(CancellationToken token = default);
Task X1_S34(CancellationToken token = default);
Task X2_S34(CancellationToken token = default);
Task X3_S34(CancellationToken token = default);
Task X1_R12(CancellationToken token = default);
Task X2_R12(CancellationToken token = default);
Task X3_R12(CancellationToken token = default);
Task X1_R43(CancellationToken token = default);
Task X2_R43(CancellationToken token = default);
Task X3_R43(CancellationToken token = default);
Task<bool> WaitCoil(Func<bool?> selector, bool target, int timeoutMs = 10000);
}

View File

@@ -0,0 +1,24 @@
namespace Lab505.Script.Facades;
/// <summary>
/// Script-friendly conveyor interface — no dependency on ConveyorState class.
/// Use State.WaitUntil(s => s.C1InOn) for condition waits.
/// </summary>
public interface IConveyorFacade
{
// ── Coil commands ──────────────────────────────────────────────
bool C1In(bool state);
bool C1Out(bool state);
bool C1IMRin(bool state);
bool C1IMRout(bool state);
bool C1Ready(bool state);
bool C2Ready(bool state);
bool C2In(bool state);
bool C2Out(bool state);
bool C1HasGoods(bool state);
bool C1NotGoods(bool state);
bool C2HasGoods(bool state);
bool C2NotGoods(bool state);
void StopAll();
}

View File

@@ -0,0 +1,11 @@
namespace Lab505.Script.Facades;
/// <summary>Script-friendly Dobot interface.</summary>
public interface IDobotFacade
{
Task PowerOn(CancellationToken t = default);
Task GoHome(CancellationToken t = default);
Task Continue(CancellationToken t = default);
Task Cancel(CancellationToken t = default);
Task Pickup(int ok, int ng, CancellationToken t = default);
}

View File

@@ -0,0 +1,10 @@
namespace Lab505.Script.Facades;
/// <summary>Subset of DobotOpcDriver methods needed by DobotFacade — breaks circular dependency.</summary>
public interface IDobotRaw
{
Task PowerOn(CancellationToken t = default);
Task GoHome(CancellationToken t = default);
Task Continue(CancellationToken t = default);
Task Cancel(CancellationToken t = default);
}

View File

@@ -0,0 +1,35 @@
namespace Lab505.Script.Facades;
/// <summary>Script facade for the IMR robot — use named positions instead of raw coordinates.</summary>
public interface IImrFacade
{
/// <summary>Move to named position. Positions: "C1", "ABB"</summary>
Task GoTo(string position, CancellationToken ct = default);
/// <summary>Undock from a named docked position. Positions: "C1", "ABB"</summary>
Task Undock(string fromPosition, CancellationToken ct = default);
/// <summary>Load items onto the robot via VDA</summary>
Task Load(CancellationToken ct = default);
/// <summary>Unload items from the robot via VDA</summary>
Task Unload(CancellationToken ct = default);
/// <summary>Pick up items. ok = number of OK items, ng = number of NG items</summary>
Task PickUp(int ok, int ng = 0, CancellationToken ct = default);
/// <summary>Pause the robot's current task (VDA startPause)</summary>
Task Pause(CancellationToken ct = default);
/// <summary>Resume a paused task (VDA stopPause)</summary>
Task Resume(CancellationToken ct = default);
/// <summary>Re-initialize the robot's pose (x, y in metres, theta in radians)</summary>
Task InitPosition(double x, double y, double theta, CancellationToken ct = default);
/// <summary>Cancel current task</summary>
Task Cancel(CancellationToken ct = default);
/// <summary>Check if robot is currently at named position</summary>
bool IsAt(string position, double tol = 0.2);
}

View File

@@ -0,0 +1,22 @@
namespace Lab505.Script.Facades;
/// <summary>Subset of ImrVdaDriver methods needed by ImrFacade — breaks circular dependency.</summary>
public interface IImrRaw
{
Task DockToStation(string target, CancellationToken t = default);
Task<string> UndockFromStation_IMR(double d, double v, CancellationToken t = default);
Task<string> Load_Vda(CancellationToken t = default);
Task<string> Unload_Vda(CancellationToken t = default);
Task<string> PickUp_Vda(int ok, int ng, CancellationToken t = default);
Task<string> StartPause(CancellationToken t = default);
Task<string> StopPause(CancellationToken t = default);
Task<string> InitPosition(double x, double y, double theta, CancellationToken t = default);
Task Cancel_Vda(CancellationToken t = default);
bool IsAtPosition(double tx, double ty, double tol = 0.2);
/// <summary>Chờ action có ActionID cụ thể đạt FINISHED. Throw nếu FAILED/ABORTED hoặc timeout.</summary>
Task WaitActionIdCompleted(string actionId, int timeoutMs, CancellationToken ct = default);
/// <summary>Chờ MoveTo hoàn thành — dựa vào NBR false→true.</summary>
Task WaitMoveTo(int timeoutMs, CancellationToken ct = default);
}

View File

@@ -0,0 +1,32 @@
using Lab505.Script.Facades;
namespace Lab505.Script;
public class FlowContext
{
/// <summary>System condition checker — Assert(instant) / WaitUntil(async wait) / Require(wait+throw)</summary>
public required ICondition State { get; set; }
/// <summary>IMR facade — GoTo, Undock, Load, Unload, PickUp, IsAt</summary>
public required IImrFacade IMR { get; set; }
/// <summary>AMR facade — GoTo, Undock, Load, Unload, IsAt</summary>
public required IAmrFacade AMR { get; set; }
/// <summary>Conveyor — C1In/C1Out/C2In/C2Out coil commands</summary>
public required IConveyorFacade Conveyor { get; set; }
/// <summary>ASRS — X1_S12…X3_R43 operations + WaitCoil</summary>
public required IAsrsFacade ASRS { get; set; }
/// <summary>Dobot — PowerOn, GoHome, Continue, Cancel, Pickup</summary>
public required IDobotFacade Dobot { get; set; }
/// <summary>Workflow — read-only state: IsRunning, LastError, CompletedCycles</summary>
public required IFlowFacade Workflow { get; set; }
/// <summary>Per-user output writer — use Log.WriteLine(...) in scripts instead of Console.WriteLine</summary>
public required TextWriter Log { get; set; }
public CancellationToken Token { get; set; }
}

View File

@@ -0,0 +1,61 @@
namespace Lab505.Script;
/// <summary>
/// Unified condition checker exposed to user scripts.
/// Type 1 — instant: State.Assert(s => s.ImrReady, "msg")
/// Type 2 — async wait: await State.WaitUntil(s => s.ImrReadyAtC1)
/// await State.Require(s => s.C1HasGoods, "msg")
/// </summary>
public interface ICondition
{
// ── IMR ──────────────────────────────────────────────────────────────
bool ImrOnline { get; }
bool ImrReady { get; }
bool ImrBusy { get; }
bool ImrAtC1 { get; }
bool ImrAtABB { get; }
bool ImrReadyAtC1 { get; }
bool ImrReadyAtABB { get; }
// ── AMR ──────────────────────────────────────────────────────────────
bool AmrOnline { get; }
bool AmrReady { get; }
bool AmrBusy { get; }
bool AmrAtCap1 { get; }
bool AmrAtCap2 { get; }
bool AmrReadyAtCap1 { get; }
bool AmrReadyAtCap2 { get; }
// ── C1 ───────────────────────────────────────────────────────────────
bool C1Online { get; }
bool C1HasGoods { get; }
bool C1NotGoods { get; }
bool C1Ready { get; }
bool C1Idle { get; }
bool C1InOn { get; }
bool C1OutOn { get; }
bool C1IMRinOn { get; }
bool C1IMRoutOn { get; }
// ── C2 ───────────────────────────────────────────────────────────────
bool C2Online { get; }
bool C2HasGoods { get; }
bool C2Ready { get; }
bool C2Idle { get; }
bool C2InOn { get; }
bool C2OutOn { get; }
// ── Dobot ────────────────────────────────────────────────────────────
bool DobotOnline { get; }
// ── Condition methods ─────────────────────────────────────────────────
/// <summary>Instant check — throws InvalidOperationException if false. Use before sending a command.</summary>
void Assert(Func<ICondition, bool> condition, string errorMessage);
/// <summary>Event-driven wait. Returns false on timeout, throws on cancellation.</summary>
Task<bool> WaitUntil(Func<ICondition, bool> condition, int timeoutMs = 1_200_000, CancellationToken ct = default);
/// <summary>Event-driven wait. Throws TimeoutException if condition not met in time.</summary>
Task Require(Func<ICondition, bool> condition, string errorMessage, int timeoutMs = 1_200_000, CancellationToken ct = default);
}

View File

@@ -0,0 +1,10 @@
namespace Lab505.Script;
/// <summary>Read-only view of FlowService state for use in scripts.</summary>
public interface IFlowFacade
{
bool IsRunning { get; }
string? LastError { get; }
int CompletedCycles { get; }
event Action? RunningStateChanged;
}

View File

@@ -0,0 +1,90 @@
using Lab505.Script.Facades;
using Lab505.Shared;
namespace Lab505.Script;
/// <summary>Script facade for IMR — maps named positions to driver calls.</summary>
public class ImrFacade : IImrFacade
{
private readonly IImrRaw _drv;
// Timeout khớp với FlowService — script tuần tự chờ action/NBR trước khi trả về.
private const int ACTION_TIMEOUT_MS = 20 * 60 * 1000;
private const int POS_TIMEOUT_MS = 30 * 60 * 1000;
private static readonly Dictionary<string, (string vda, double x, double y)> _pos =
new(StringComparer.OrdinalIgnoreCase)
{
["C1"] = ("Bt1", RobotPositions.IMR_C1_X, RobotPositions.IMR_C1_Y),
["ABB"] = ("Abb", RobotPositions.IMR_ABB_X, RobotPositions.IMR_ABB_Y),
};
private static readonly Dictionary<string, double> _undockDist =
new(StringComparer.OrdinalIgnoreCase)
{
["C1"] = RobotPositions.IMR_UNDOCK_C1,
["ABB"] = RobotPositions.IMR_UNDOCK_ABB,
};
public ImrFacade(IImrRaw drv) => _drv = drv;
public async Task GoTo(string position, CancellationToken ct = default)
{
if (!_pos.TryGetValue(position, out var p))
throw new ArgumentException($"IMR: unknown position '{position}'. Valid: {string.Join(", ", _pos.Keys)}");
await _drv.DockToStation(p.vda, ct);
await _drv.WaitMoveTo(POS_TIMEOUT_MS, ct);
}
public async Task Undock(string fromPosition, CancellationToken ct = default)
{
if (!_undockDist.TryGetValue(fromPosition, out double dist))
throw new ArgumentException($"IMR: unknown undock position '{fromPosition}'. Valid: {string.Join(", ", _undockDist.Keys)}");
var id = await _drv.UndockFromStation_IMR(-dist, RobotPositions.IMR_UNDOCK_VEL, ct);
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
}
public async Task Load(CancellationToken ct = default)
{
var id = await _drv.Load_Vda(ct);
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
}
public async Task Unload(CancellationToken ct = default)
{
var id = await _drv.Unload_Vda(ct);
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
}
public async Task PickUp(int ok, int ng = 0, CancellationToken ct = default)
{
var id = await _drv.PickUp_Vda(ok, ng, ct);
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
}
public async Task Pause(CancellationToken ct = default)
{
var id = await _drv.StartPause(ct);
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
}
public async Task Resume(CancellationToken ct = default)
{
var id = await _drv.StopPause(ct);
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
}
public async Task InitPosition(double x, double y, double theta, CancellationToken ct = default)
{
var id = await _drv.InitPosition(x, y, theta, ct);
await _drv.WaitActionIdCompleted(id, ACTION_TIMEOUT_MS, ct);
}
public Task Cancel(CancellationToken ct = default) => _drv.Cancel_Vda(ct);
public bool IsAt(string position, double tol = 0.2)
{
if (!_pos.TryGetValue(position, out var p)) return false;
return _drv.IsAtPosition(p.x, p.y, tol);
}
}

View File

@@ -0,0 +1,23 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<GenerateDocumentationFile>true</GenerateDocumentationFile>
<NoWarn>1591</NoWarn>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp.Scripting" Version="5.3.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\Lab505.Shared\Lab505.Shared.csproj" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,48 @@
namespace Lab505.Script;
/// <summary>
/// Ensures only one user runs a script in REAL mode at a time.
/// Thread-safe lock with owner info for display.
/// </summary>
public sealed class RealSessionService
{
private readonly object _lock = new();
public record SessionInfo(int UserId, string Username, DateTime AcquiredAt);
public SessionInfo? Current { get; private set; }
public event Action? OnChanged;
/// <summary>
/// Try to acquire the real-mode lock for a user.
/// Returns true if acquired (or user already holds it), false if someone else holds it.
/// </summary>
public bool TryAcquire(int userId, string username)
{
lock (_lock)
{
if (Current is null)
{
Current = new SessionInfo(userId, username, DateTime.Now);
OnChanged?.Invoke();
return true;
}
return Current.UserId == userId; // same user can re-acquire
}
}
/// <summary>Release the lock. Only the owner or a forced release.</summary>
public void Release(int userId, bool force = false)
{
lock (_lock)
{
if (Current is null) return;
if (!force && Current.UserId != userId) return;
Current = null;
OnChanged?.Invoke();
}
}
public bool IsLocked => Current is not null;
}

View File

@@ -0,0 +1,29 @@
using System.Text;
using Microsoft.AspNetCore.SignalR;
namespace Lab505.Script;
public class RealtimeWriter : TextWriter
{
private readonly IHubContext<ScriptHub> _hub;
private readonly string? _userGroup; // "user-{uid}" — routes to all tabs of one user
public override Encoding Encoding => Encoding.UTF8;
public RealtimeWriter(IHubContext<ScriptHub> hub, string? userId = null)
{
_hub = hub;
_userGroup = userId is not null ? $"user-{userId}" : null;
}
public override void WriteLine(string? value) => Send(value ?? "");
public override void Write(string? value) => Send(value ?? "");
private void Send(string value)
{
var target = _userGroup is not null
? _hub.Clients.Group(_userGroup)
: _hub.Clients.All; // fallback only (should not happen in practice)
target.SendAsync("scriptLog", value);
}
}

View File

@@ -0,0 +1,39 @@
namespace Lab505.Script;
/// <summary>Per-user CancellationTokenSource registry. Thread-safe.</summary>
public sealed class ScriptCancelService
{
private readonly object _lock = new();
private readonly Dictionary<int, CancellationTokenSource> _map = new();
public CancellationToken Register(int userId, out CancellationTokenSource cts)
{
lock (_lock)
{
if (_map.TryGetValue(userId, out var old)) { old.Cancel(); old.Dispose(); }
cts = new CancellationTokenSource();
_map[userId] = cts;
return cts.Token;
}
}
public void Cancel(int userId)
{
lock (_lock)
{
if (_map.TryGetValue(userId, out var cts)) cts.Cancel();
}
}
public void Clear(int userId)
{
lock (_lock)
{
if (_map.TryGetValue(userId, out var cts)) { cts.Dispose(); _map.Remove(userId); }
}
}
// Legacy single-user helpers (kept for backward compat)
public void Cancel() { lock (_lock) { foreach (var c in _map.Values) c.Cancel(); } }
public void Clear() { lock (_lock) { foreach (var c in _map.Values) c.Dispose(); _map.Clear(); } }
}

View File

@@ -0,0 +1,90 @@
using Microsoft.AspNetCore.SignalR;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using Microsoft.CodeAnalysis.Scripting;
using System.Reflection;
using System.Text.Json;
namespace Lab505.Script;
public class ScriptEngine
{
private readonly ScriptOptions _baseOptions;
private readonly IHubContext<ScriptHub> _hub;
public ScriptEngine(IHubContext<ScriptHub> hub, string[]? extraImports = null, Assembly[]? extraAssemblies = null)
{
_hub = hub;
var imports = new List<string>
{
"System",
"System.Threading",
"System.Threading.Tasks",
"Lab505.Script.Facades",
"Lab505.Shared",
};
if (extraImports != null) imports.AddRange(extraImports);
var refs = new List<Assembly>
{
typeof(Task).Assembly,
typeof(ScriptEngine).Assembly, // Lab505.Script itself
};
if (extraAssemblies != null) refs.AddRange(extraAssemblies);
_baseOptions = ScriptOptions.Default
.WithImports(imports)
.WithReferences(refs);
}
public async Task<string> ExecuteAsync(string code, object? globals = null, CancellationToken token = default,
string? userId = null)
{
var options = globals != null
? _baseOptions.AddReferences(globals.GetType().Assembly)
: _baseOptions;
var script = CSharpScript.Create(
code,
options: options,
globalsType: globals?.GetType()
);
var writer = new RealtimeWriter(_hub, userId);
// Set per-user Log on the globals (thread-safe — no global Console mutation)
if (globals is FlowContext sg) sg.Log = writer;
try
{
ScriptState<object>? state = globals != null
? await script.RunAsync(globals, token)
: await script.RunAsync(cancellationToken: token);
return state?.ReturnValue != null ? Pretty(state.ReturnValue) : "";
}
catch (CompilationErrorException ex)
{
writer.WriteLine("❌ Compile error:");
foreach (var d in ex.Diagnostics)
writer.WriteLine(" " + d);
return "";
}
}
private static string Pretty(object value)
{
var type = value.GetType();
if (type.IsPrimitive || value is string || value is decimal)
return value.ToString() ?? "";
if (type.IsArray)
return "[" + string.Join(", ", ((Array)value).Cast<object>()) + "]";
if (value is System.Collections.IEnumerable en)
{
var items = new List<string>();
foreach (var item in en) items.Add(item?.ToString() ?? "");
return "[" + string.Join(", ", items) + "]";
}
return JsonSerializer.Serialize(value);
}
}

View File

@@ -0,0 +1,27 @@
using Microsoft.AspNetCore.SignalR;
using System.Security.Claims;
namespace Lab505.Script;
/// <summary>
/// SignalR hub for script execution. Each user's connection is added to group "user-{uid}"
/// so the server can push sim-panel state to a specific user via Clients.Group.
/// </summary>
public class ScriptHub : Hub
{
public override async Task OnConnectedAsync()
{
var uid = Context.User?.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid is not null)
await Groups.AddToGroupAsync(Context.ConnectionId, $"user-{uid}");
await base.OnConnectedAsync();
}
public override async Task OnDisconnectedAsync(Exception? exception)
{
var uid = Context.User?.FindFirstValue(ClaimTypes.NameIdentifier);
if (uid is not null)
await Groups.RemoveFromGroupAsync(Context.ConnectionId, $"user-{uid}");
await base.OnDisconnectedAsync(exception);
}
}

View File

@@ -0,0 +1,47 @@
using Lab505.Script.Facades;
namespace Lab505.Script.Sim;
/// <summary>Per-user in-memory AMR simulation. All operations complete after a fixed delay.</summary>
public sealed class SimAmr : IAmrFacade
{
private const int MoveDelayMs = 1500;
private const int ActionDelayMs = 800;
private string _position = "Cap1";
public string Position => _position;
public event Action<string>? OnMoved;
public bool IsAt(string position, double tol = 0.2) =>
string.Equals(_position, position, StringComparison.OrdinalIgnoreCase);
public async Task GoTo(string position, CancellationToken ct = default)
{
await Task.Delay(MoveDelayMs, ct);
_position = position;
OnMoved?.Invoke(_position);
}
public async Task Undock(CancellationToken ct = default) =>
await Task.Delay(ActionDelayMs, ct);
public async Task Load(CancellationToken ct = default) =>
await Task.Delay(ActionDelayMs, ct);
public async Task Unload(CancellationToken ct = default) =>
await Task.Delay(ActionDelayMs, ct);
public async Task Pause(CancellationToken ct = default) =>
await Task.Delay(ActionDelayMs, ct);
public async Task Resume(CancellationToken ct = default) =>
await Task.Delay(ActionDelayMs, ct);
public async Task InitPosition(double x, double y, double theta, CancellationToken ct = default) =>
await Task.Delay(ActionDelayMs, ct);
public async Task Cancel(CancellationToken ct = default) =>
await Task.Delay(200, ct);
}

View File

@@ -0,0 +1,43 @@
using Lab505.Script.Facades;
namespace Lab505.Script.Sim;
/// <summary>Per-user in-memory ASRS simulation. All operations complete after a fixed delay.</summary>
public sealed class SimAsrs : IAsrsFacade
{
private const int OpDelayMs = 1200;
public bool IsBusy { get; private set; }
public event Action? OnOperationStateChanged;
public bool IsLocked(string key) => false;
private async Task RunOp(CancellationToken token)
{
IsBusy = true;
OnOperationStateChanged?.Invoke();
try { await Task.Delay(OpDelayMs, token); }
finally
{
IsBusy = false;
OnOperationStateChanged?.Invoke();
}
}
public Task SYSTEM_HOMING(CancellationToken token = default) => RunOp(token);
public Task X1_S12(CancellationToken token = default) => RunOp(token);
public Task X2_S12(CancellationToken token = default) => RunOp(token);
public Task X3_S12(CancellationToken token = default) => RunOp(token);
public Task X1_S34(CancellationToken token = default) => RunOp(token);
public Task X2_S34(CancellationToken token = default) => RunOp(token);
public Task X3_S34(CancellationToken token = default) => RunOp(token);
public Task X1_R12(CancellationToken token = default) => RunOp(token);
public Task X2_R12(CancellationToken token = default) => RunOp(token);
public Task X3_R12(CancellationToken token = default) => RunOp(token);
public Task X1_R43(CancellationToken token = default) => RunOp(token);
public Task X2_R43(CancellationToken token = default) => RunOp(token);
public Task X3_R43(CancellationToken token = default) => RunOp(token);
public Task<bool> WaitCoil(Func<bool?> selector, bool target, int timeoutMs = 10000) =>
Task.FromResult(true);
}

View File

@@ -0,0 +1,26 @@
namespace Lab505.Script.Sim;
/// <summary>
/// Isolated per-user simulation context.
/// Each FlowContext built from this context has its own independent robot state.
/// </summary>
public sealed class SimContext
{
public SimConveyor Conveyor { get; } = new();
public SimImr IMR { get; } = new();
public SimAmr AMR { get; } = new();
public SimAsrs ASRS { get; } = new();
public SimDobot Dobot { get; } = new();
public SimFlow Workflow { get; }
/// <summary>Fires whenever any simulated robot/device changes state.</summary>
public event Action? OnChanged;
public SimContext()
{
Workflow = new SimFlow(this);
IMR.OnMoved += _ => OnChanged?.Invoke();
AMR.OnMoved += _ => OnChanged?.Invoke();
Conveyor.OnChanged += () => OnChanged?.Invoke();
}
}

View File

@@ -0,0 +1,68 @@
using Lab505.Script.Facades;
namespace Lab505.Script.Sim;
/// <summary>
/// Per-user in-memory conveyor simulation.
/// Coil commands set state immediately then fire "feedback" after a short delay
/// (simulating the physical conveyor responding). WaitCx methods watch for feedback.
/// </summary>
public sealed class SimConveyor : IConveyorFacade
{
// Feedback state (what WaitCx methods watch)
private bool? _c1In, _c1Out, _c1IMRin, _c1IMRout, _c1Ready, _c2Ready;
private bool? _c2In, _c2Out;
private bool? _c1HasGoods, _c1NotGoods, _c2HasGoods, _c2NotGoods;
// Read-only accessors for state snapshot
public bool? StateC1In => _c1In;
public bool? StateC1Out => _c1Out;
public bool? StateC1IMRin => _c1IMRin;
public bool? StateC1IMRout => _c1IMRout;
public bool? StateC1Ready => _c1Ready;
public bool? StateC2Ready => _c2Ready;
public bool? StateC2In => _c2In;
public bool? StateC2Out => _c2Out;
public bool? StateC1HasGoods => _c1HasGoods;
public bool? StateC1NotGoods => _c1NotGoods;
public bool? StateC2HasGoods => _c2HasGoods;
public bool? StateC2NotGoods => _c2NotGoods;
public event Action? OnChanged;
private const int FeedbackDelayMs = 600;
// ── Coil commands ──────────────────────────────────────────────────────────
public bool C1In(bool v) => FireFeedback(v, x => _c1In = x);
public bool C1Out(bool v) => FireFeedback(v, x => _c1Out = x);
public bool C1IMRin(bool v) => FireFeedback(v, x => _c1IMRin = x);
public bool C1IMRout(bool v) => FireFeedback(v, x => _c1IMRout = x);
public bool C1Ready(bool v) => FireFeedback(v, x => _c1Ready = x);
public bool C2Ready(bool v) => FireFeedback(v, x => _c2Ready = x);
public bool C2In(bool v) => FireFeedback(v, x => _c2In = x);
public bool C2Out(bool v) => FireFeedback(v, x => _c2Out = x);
public bool C1HasGoods(bool v) => FireFeedback(v, x => _c1HasGoods = x);
public bool C1NotGoods(bool v) => FireFeedback(v, x => _c1NotGoods = x);
public bool C2HasGoods(bool v) => FireFeedback(v, x => _c2HasGoods = x);
public bool C2NotGoods(bool v) => FireFeedback(v, x => _c2NotGoods = x);
public void StopAll()
{
C1In(false); C1Out(false); C1IMRin(false); C1IMRout(false);
C2In(false); C2Out(false);
}
// ── Internal helpers ───────────────────────────────────────────────────────
private bool FireFeedback(bool value, Action<bool> setter)
{
_ = Task.Run(async () =>
{
await Task.Delay(FeedbackDelayMs);
setter(value);
OnChanged?.Invoke();
});
return true;
}
}

View File

@@ -0,0 +1,15 @@
using Lab505.Script.Facades;
namespace Lab505.Script.Sim;
/// <summary>Per-user in-memory Dobot simulation. All operations complete after a fixed delay.</summary>
public sealed class SimDobot : IDobotFacade
{
private const int OpDelayMs = 800;
public Task PowerOn(CancellationToken t = default) => Task.Delay(OpDelayMs, t);
public Task GoHome(CancellationToken t = default) => Task.Delay(OpDelayMs, t);
public Task Continue(CancellationToken t = default) => Task.Delay(OpDelayMs, t);
public Task Cancel(CancellationToken t = default) => Task.Delay(200, t);
public Task Pickup(int ok, int ng, CancellationToken t = default) => Task.Delay(OpDelayMs, t);
}

View File

@@ -0,0 +1,126 @@
using Lab505.Script;
namespace Lab505.Script.Sim;
/// <summary>
/// Per-user in-memory workflow simulation.
/// Each X_A/X_B call runs a full 8-step cycle using SimContext robots with fixed delays.
/// </summary>
public sealed class SimFlow : IFlowFacade
{
private readonly SimImr _imr;
private readonly SimAmr _amr;
private readonly SimConveyor _conv;
private readonly SimAsrs _asrs;
private readonly SimDobot _dobot;
public bool IsRunning { get; private set; }
public string? LastError { get; private set; }
public int CompletedCycles { get; private set; }
public event Action? RunningStateChanged;
internal SimFlow(SimContext ctx)
{
_imr = ctx.IMR;
_amr = ctx.AMR;
_conv = ctx.Conveyor;
_asrs = ctx.ASRS;
_dobot = ctx.Dobot;
}
// ── X_A: S34 pick → workflow → S34 return ────────────────────────────────
public Task X1A(int times, int ng, CancellationToken ct = default)
=> RunCycle(times, ng, ct => _asrs.X1_S34(ct), ct => _asrs.X1_R43(ct), ct);
public Task X2A(int times, int ng, CancellationToken ct = default)
=> RunCycle(times, ng, ct => _asrs.X2_S34(ct), ct => _asrs.X2_R43(ct), ct);
public Task X3A(int times, int ng, CancellationToken ct = default)
=> RunCycle(times, ng, ct => _asrs.X3_S34(ct), ct => _asrs.X3_R43(ct), ct);
// ── X_B: S12 pick → workflow → S12 return ────────────────────────────────
public Task X1B(int times, int ng, CancellationToken ct = default)
=> RunCycle(times, ng, ct => _asrs.X1_S12(ct), ct => _asrs.X1_R12(ct), ct);
public Task X2B(int times, int ng, CancellationToken ct = default)
=> RunCycle(times, ng, ct => _asrs.X2_S12(ct), ct => _asrs.X2_R12(ct), ct);
public Task X3B(int times, int ng, CancellationToken ct = default)
=> RunCycle(times, ng, ct => _asrs.X3_S12(ct), ct => _asrs.X3_R12(ct), ct);
// ── Run cycle (no ASRS) ───────────────────────────────────────────────────
public Task RunCycle(int times, int ng, CancellationToken ct = default)
=> RunCycle(times, ng, _ => Task.CompletedTask, _ => Task.CompletedTask, ct);
// ── Core cycle loop ───────────────────────────────────────────────────────
private async Task RunCycle(
int times, int ng,
Func<CancellationToken, Task> startOp,
Func<CancellationToken, Task> endOp,
CancellationToken ct)
{
IsRunning = true;
LastError = null;
RunningStateChanged?.Invoke();
try
{
for (int i = 0; i < times; i++)
{
ct.ThrowIfCancellationRequested();
// Step 1: Init — IMR→C1 + AMR→Cap2 + ASRS pick (parallel)
await Task.WhenAll(_imr.GoTo("C1", ct), _amr.GoTo("Cap2", ct), startOp(ct));
// Step 2: AMR load from C2
_conv.C2Out(true);
await _amr.Load(ct);
_conv.C2Out(false);
// Step 3: AMR undock → Cap1
await _amr.Undock(ct);
await _amr.GoTo("Cap1", ct);
// Step 4: AMR→IMR exchange via C1
_conv.C1In(true);
await _imr.Load(ct);
_conv.C1In(false);
_conv.C1Out(true);
await Task.Delay(300, ct);
_conv.C1Out(false);
// Step 5: IMR process @ ABB
await _imr.GoTo("ABB", ct);
await _dobot.Pickup(1, ng, ct);
await _imr.GoTo("C1", ct);
// Step 6: IMR→AMR exchange via C1
_conv.C1IMRin(true);
await _imr.Unload(ct);
_conv.C1IMRin(false);
await _amr.Load(ct);
// Step 7: AMR → Cap2
await _amr.GoTo("Cap2", ct);
// Step 8: AMR unload to C2 + ASRS return
_conv.C2In(true);
await _amr.Unload(ct);
_conv.C2In(false);
await endOp(ct);
CompletedCycles++;
}
}
catch (OperationCanceledException) { throw; }
catch (Exception ex)
{
LastError = ex.Message;
throw;
}
finally
{
IsRunning = false;
RunningStateChanged?.Invoke();
}
}
}

View File

@@ -0,0 +1,50 @@
using Lab505.Script.Facades;
namespace Lab505.Script.Sim;
/// <summary>Per-user in-memory IMR simulation. All operations complete after a fixed delay.</summary>
public sealed class SimImr : IImrFacade
{
private const int MoveDelayMs = 1500;
private const int ActionDelayMs = 800;
private string _position = "C1";
public string Position => _position;
public event Action<string>? OnMoved;
public bool IsAt(string position, double tol = 0.2) =>
string.Equals(_position, position, StringComparison.OrdinalIgnoreCase);
public async Task GoTo(string position, CancellationToken ct = default)
{
await Task.Delay(MoveDelayMs, ct);
_position = position;
OnMoved?.Invoke(_position);
}
public async Task Undock(string fromPosition, CancellationToken ct = default) =>
await Task.Delay(ActionDelayMs, ct);
public async Task Load(CancellationToken ct = default) =>
await Task.Delay(ActionDelayMs, ct);
public async Task Unload(CancellationToken ct = default) =>
await Task.Delay(ActionDelayMs, ct);
public async Task PickUp(int ok, int ng = 0, CancellationToken ct = default) =>
await Task.Delay(ActionDelayMs, ct);
public async Task Pause(CancellationToken ct = default) =>
await Task.Delay(ActionDelayMs, ct);
public async Task Resume(CancellationToken ct = default) =>
await Task.Delay(ActionDelayMs, ct);
public async Task InitPosition(double x, double y, double theta, CancellationToken ct = default) =>
await Task.Delay(ActionDelayMs, ct);
public async Task Cancel(CancellationToken ct = default) =>
await Task.Delay(200, ct);
}