481 lines
21 KiB
C#
481 lines
21 KiB
C#
namespace Lab505.Domain.Entities;
|
|
|
|
// ═══════════════════════════════════════════════════════════════
|
|
// VDA5050 Action Status
|
|
// ═══════════════════════════════════════════════════════════════
|
|
|
|
public enum VdaActionStatus
|
|
{
|
|
Initializing,
|
|
Running,
|
|
Finished,
|
|
Failed,
|
|
Aborted
|
|
}
|
|
|
|
public static class VdaActionStatusExtensions
|
|
{
|
|
public static string ToVdaString(this VdaActionStatus s) => s switch
|
|
{
|
|
VdaActionStatus.Initializing => "INITIALIZING",
|
|
VdaActionStatus.Running => "RUNNING",
|
|
VdaActionStatus.Finished => "FINISHED",
|
|
VdaActionStatus.Failed => "FAILED",
|
|
VdaActionStatus.Aborted => "ABORTED",
|
|
_ => throw new ArgumentOutOfRangeException(nameof(s))
|
|
};
|
|
}
|
|
|
|
// ═══════════════════════════════════════════════════════════════
|
|
// VDA5050 Action Types
|
|
// ═══════════════════════════════════════════════════════════════
|
|
|
|
public static class VdaActionType
|
|
{
|
|
// MoveTo không phải action → không có ở đây
|
|
public const string Load = "load";
|
|
public const string Unload = "unload";
|
|
public const string PickUp = "pickup";
|
|
public const string UndockFromStation = "UnDockFromStation";
|
|
}
|
|
|
|
// ═══════════════════════════════════════════════════════════════
|
|
// Result types
|
|
// ═══════════════════════════════════════════════════════════════
|
|
|
|
public enum VdaCompletionPath { Action, NewBaseRequest, Timeout }
|
|
|
|
public record VdaWaitResult(
|
|
VdaCompletionPath Path,
|
|
string? ActionType = null,
|
|
string? ActionStatus = null,
|
|
string? TimeoutSnapshot = null
|
|
)
|
|
{
|
|
public bool IsTimeout => Path == VdaCompletionPath.Timeout;
|
|
public bool IsAction => Path == VdaCompletionPath.Action;
|
|
public bool IsNbr => Path == VdaCompletionPath.NewBaseRequest;
|
|
}
|
|
|
|
// ═══════════════════════════════════════════════════════════════
|
|
// Exceptions
|
|
// ═══════════════════════════════════════════════════════════════
|
|
|
|
public class RobotStateTimeoutException : Exception
|
|
{
|
|
public RobotStateTimeoutException(string message) : base(message) { }
|
|
}
|
|
|
|
public class RobotStateErrorException : Exception
|
|
{
|
|
public RobotStateErrorException(string message) : base(message) { }
|
|
}
|
|
|
|
// ═══════════════════════════════════════════════════════════════
|
|
// RobotStateWatcher
|
|
// ═══════════════════════════════════════════════════════════════
|
|
|
|
public class RobotConditionWaiter : IDisposable
|
|
{
|
|
private readonly RobotState _state;
|
|
|
|
public RobotConditionWaiter(RobotState state) => _state = state;
|
|
|
|
// ── Fluent entry points ──────────────────────────────────────
|
|
|
|
/// <summary>Tổng quát — actionType thẳng từ VDA5050 protocol.</summary>
|
|
public VdaCommandAwaiter ActionStates(string actionType)
|
|
=> new(this, actionType);
|
|
|
|
/// <summary>Semantic wrappers.</summary>
|
|
public VdaCommandAwaiter Load_Vda() => ActionStates(VdaActionType.Load);
|
|
public VdaCommandAwaiter Unload_Vda() => ActionStates(VdaActionType.Unload);
|
|
public VdaCommandAwaiter PickUp_Vda() => ActionStates(VdaActionType.PickUp);
|
|
public VdaCommandAwaiter UndockFromStation_Vda() => ActionStates(VdaActionType.UndockFromStation);
|
|
|
|
// ── Internal: check chung ActionStates + NewBaseRequest ───────
|
|
|
|
internal async Task<VdaWaitResult> WaitActionOrNbrAsync(
|
|
string actionType,
|
|
string[] targetStatuses,
|
|
TimeSpan timeout,
|
|
CancellationToken ct = default)
|
|
{
|
|
int sawNbrBusy = (_state.NewBaseRequest ?? false) ? 0 : 1;
|
|
|
|
if (_state.RawErrors.Any(e => e.ErrorLevel == "FATAL"))
|
|
throw new RobotStateErrorException(BuildErrorMessage(_state));
|
|
|
|
var tcs = new TaskCompletionSource<VdaWaitResult>(
|
|
TaskCreationOptions.RunContinuationsAsynchronously);
|
|
|
|
void OnUpdated()
|
|
{
|
|
if (_state.RawErrors.Any(e => e.ErrorLevel == "FATAL"))
|
|
{
|
|
tcs.TrySetException(new RobotStateErrorException(BuildErrorMessage(_state)));
|
|
return;
|
|
}
|
|
|
|
// Chỉ chốt theo NBR sau khi đã thấy robot bận (NBR=false) ít nhất 1 lần.
|
|
// Tránh ăn nhầm NBR=true cũ còn sót từ lệnh trước.
|
|
bool current = _state.NewBaseRequest ?? false;
|
|
if (!current)
|
|
{
|
|
Interlocked.Exchange(ref sawNbrBusy, 1);
|
|
}
|
|
else if (Volatile.Read(ref sawNbrBusy) == 1)
|
|
{
|
|
tcs.TrySetResult(new VdaWaitResult(VdaCompletionPath.NewBaseRequest));
|
|
return;
|
|
}
|
|
|
|
// ActionStates match
|
|
var action = _state.ActionStates
|
|
.FirstOrDefault(a => a.ActionType == actionType
|
|
&& targetStatuses.Contains(a.ActionStatus));
|
|
if (action != null)
|
|
tcs.TrySetResult(new VdaWaitResult(
|
|
VdaCompletionPath.Action,
|
|
ActionType: action.ActionType,
|
|
ActionStatus: action.ActionStatus));
|
|
}
|
|
|
|
_state.OnUpdated += OnUpdated;
|
|
try
|
|
{
|
|
OnUpdated(); // Re-check sau subscribe — tránh miss nếu state đã đạt trước khi subscribe
|
|
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
cts.CancelAfter(timeout);
|
|
return await tcs.Task.WaitAsync(cts.Token);
|
|
}
|
|
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
|
{
|
|
return new VdaWaitResult(VdaCompletionPath.Timeout,
|
|
TimeoutSnapshot: BuildTimeoutMessage(_state, timeout));
|
|
}
|
|
finally { _state.OnUpdated -= OnUpdated; }
|
|
}
|
|
|
|
// ── Internal: chỉ check ActionStates ─────────────────────────
|
|
|
|
internal async Task<VdaWaitResult> WaitActionOnlyAsync(
|
|
string actionType,
|
|
string targetStatus,
|
|
TimeSpan timeout,
|
|
CancellationToken ct = default)
|
|
{
|
|
if (_state.RawErrors.Any(e => e.ErrorLevel == "FATAL"))
|
|
throw new RobotStateErrorException(BuildErrorMessage(_state));
|
|
|
|
var tcs = new TaskCompletionSource<VdaWaitResult>(
|
|
TaskCreationOptions.RunContinuationsAsynchronously);
|
|
|
|
void OnUpdated()
|
|
{
|
|
if (_state.RawErrors.Any(e => e.ErrorLevel == "FATAL"))
|
|
{
|
|
tcs.TrySetException(new RobotStateErrorException(BuildErrorMessage(_state)));
|
|
return;
|
|
}
|
|
|
|
var action = _state.ActionStates
|
|
.FirstOrDefault(a => a.ActionType == actionType
|
|
&& a.ActionStatus == targetStatus);
|
|
if (action != null)
|
|
tcs.TrySetResult(new VdaWaitResult(
|
|
VdaCompletionPath.Action,
|
|
ActionType: action.ActionType,
|
|
ActionStatus: action.ActionStatus));
|
|
}
|
|
|
|
_state.OnUpdated += OnUpdated;
|
|
try
|
|
{
|
|
OnUpdated(); // Re-check sau subscribe — tránh miss nếu state đã đạt trước khi subscribe
|
|
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
cts.CancelAfter(timeout);
|
|
return await tcs.Task.WaitAsync(cts.Token);
|
|
}
|
|
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
|
{
|
|
return new VdaWaitResult(VdaCompletionPath.Timeout,
|
|
TimeoutSnapshot: BuildTimeoutMessage(_state, timeout));
|
|
}
|
|
finally { _state.OnUpdated -= OnUpdated; }
|
|
}
|
|
|
|
// ── Internal: chờ ActionId cụ thể đạt terminal status ────────
|
|
|
|
/// <summary>
|
|
/// Chờ action CÓ ActionID cụ thể đạt FINISHED (hoặc throw nếu FAILED/ABORTED).
|
|
/// Tránh bắt nhầm action FINISHED cũ còn sót lại trong ActionStates.
|
|
/// </summary>
|
|
internal async Task WaitActionIdCompletedAsync(
|
|
string actionId,
|
|
TimeSpan timeout,
|
|
CancellationToken ct = default)
|
|
{
|
|
if (_state.RawErrors.Any(e => e.ErrorLevel == "FATAL"))
|
|
throw new RobotStateErrorException(BuildErrorMessage(_state));
|
|
|
|
var tcs = new TaskCompletionSource(
|
|
TaskCreationOptions.RunContinuationsAsynchronously);
|
|
|
|
void OnUpdated()
|
|
{
|
|
if (_state.RawErrors.Any(e => e.ErrorLevel == "FATAL"))
|
|
{
|
|
tcs.TrySetException(new RobotStateErrorException(BuildErrorMessage(_state)));
|
|
return;
|
|
}
|
|
|
|
var action = _state.ActionStates.FirstOrDefault(a => a.ActionID == actionId);
|
|
if (action is null) return; // chưa thấy — robot chưa nhận lệnh
|
|
|
|
switch (action.ActionStatus)
|
|
{
|
|
case "FINISHED":
|
|
tcs.TrySetResult();
|
|
break;
|
|
case "FAILED":
|
|
case "ABORTED":
|
|
tcs.TrySetException(new RobotStateErrorException(
|
|
$"[{action.ActionType}#{actionId}] kết thúc với trạng thái {action.ActionStatus}"));
|
|
break;
|
|
}
|
|
}
|
|
|
|
_state.OnUpdated += OnUpdated;
|
|
try
|
|
{
|
|
OnUpdated();
|
|
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
cts.CancelAfter(timeout);
|
|
await tcs.Task.WaitAsync(cts.Token);
|
|
}
|
|
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
|
{
|
|
var seen = _state.ActionStates.Any(a => a.ActionID == actionId);
|
|
throw new RobotStateTimeoutException(
|
|
$"Action#{actionId} {(seen ? "chưa hoàn thành" : "robot chưa nhận lệnh (không thấy ActionID trong state)")} — " +
|
|
BuildTimeoutMessage(_state, timeout));
|
|
}
|
|
finally { _state.OnUpdated -= OnUpdated; }
|
|
}
|
|
|
|
public Task WaitActionIdCompleted(string actionId, TimeSpan timeout, CancellationToken ct = default)
|
|
=> WaitActionIdCompletedAsync(actionId, timeout, ct);
|
|
|
|
// ── Internal: chỉ check NewBaseRequest ───────────────────────
|
|
|
|
internal async Task WaitNbrOnlyAsync(
|
|
TimeSpan timeout,
|
|
CancellationToken ct = default)
|
|
{
|
|
// Chỉ hoàn thành khi thấy đủ chu kỳ NBR: true -> false -> true.
|
|
// Như vậy sẽ không dính NBR=true cũ của lệnh trước.
|
|
|
|
if (_state.RawErrors.Any(e => e.ErrorLevel == "FATAL"))
|
|
throw new RobotStateErrorException(BuildErrorMessage(_state));
|
|
|
|
var tcs = new TaskCompletionSource(
|
|
TaskCreationOptions.RunContinuationsAsynchronously);
|
|
|
|
var phase = _state.NewBaseRequest == true ? 1 : 0;
|
|
// phase 0: chờ trạng thái sẵn sàng ban đầu (NBR=true)
|
|
// phase 1: đã thấy true, chờ robot bận (NBR=false)
|
|
// phase 2: đã thấy false, chờ robot ready lại (NBR=true)
|
|
|
|
void OnUpdated()
|
|
{
|
|
if (_state.RawErrors.Any(e => e.ErrorLevel == "FATAL"))
|
|
{
|
|
tcs.TrySetException(new RobotStateErrorException(BuildErrorMessage(_state)));
|
|
return;
|
|
}
|
|
|
|
bool current = _state.NewBaseRequest ?? false;
|
|
switch (Volatile.Read(ref phase))
|
|
{
|
|
case 0:
|
|
if (current)
|
|
Interlocked.CompareExchange(ref phase, 1, 0);
|
|
return;
|
|
|
|
case 1:
|
|
if (!current)
|
|
Interlocked.CompareExchange(ref phase, 2, 1);
|
|
return;
|
|
|
|
case 2:
|
|
if (current)
|
|
tcs.TrySetResult();
|
|
return;
|
|
}
|
|
}
|
|
|
|
_state.OnUpdated += OnUpdated;
|
|
try
|
|
{
|
|
OnUpdated(); // Re-check sau subscribe — bắt race nếu NBR chuyển false→true đúng lúc subscribe
|
|
using var cts = CancellationTokenSource.CreateLinkedTokenSource(ct);
|
|
cts.CancelAfter(timeout);
|
|
await tcs.Task.WaitAsync(cts.Token);
|
|
}
|
|
catch (OperationCanceledException) when (!ct.IsCancellationRequested)
|
|
{
|
|
throw new RobotStateTimeoutException(
|
|
BuildTimeoutMessage(_state, timeout));
|
|
}
|
|
finally { _state.OnUpdated -= OnUpdated; }
|
|
}
|
|
|
|
|
|
public void Dispose() { }
|
|
|
|
// ── Helpers ──────────────────────────────────────────────────
|
|
|
|
private static string BuildErrorMessage(RobotState s)
|
|
{
|
|
var rawErrs = s.RawErrors.Select(e =>
|
|
$"[{e.ErrorLevel}] {e.ErrorType}: {e.ErrorDescription}" +
|
|
(e.ErrorReferences?.Length > 0
|
|
? " (" + string.Join(", ",
|
|
e.ErrorReferences.Select(r => $"{r.ReferenceKey}={r.ReferenceValue}")) + ")"
|
|
: ""));
|
|
var actions = s.ActionStates.Select(a => $"{a.ActionType}:{a.ActionStatus}");
|
|
return $"Errors=[{string.Join(" | ", rawErrs)}] Actions=[{string.Join(", ", actions)}]";
|
|
}
|
|
|
|
private static string BuildTimeoutMessage(RobotState s, TimeSpan timeout)
|
|
{
|
|
var rawErrs = s.RawErrors.Select(e => $"[{e.ErrorLevel}] {e.ErrorType}: {e.ErrorDescription}");
|
|
var actions = s.ActionStates.Select(a => $"{a.ActionType}:{a.ActionStatus}");
|
|
return $"Timeout {timeout.TotalSeconds}s — " +
|
|
$"Online={s.IsOnline_Vda}, " +
|
|
$"Pos=({s.X_Vda:F3}, {s.Y_Vda:F3}, θ={s.Theta_Vda:F3}), " +
|
|
$"NewBaseRequest={s.NewBaseRequest}, " +
|
|
$"Actions=[{string.Join(", ", actions)}], " +
|
|
$"Errors=[{string.Join(" | ", rawErrs)}]";
|
|
}
|
|
// Trong RobotStateWatcher
|
|
/// <summary>Chờ MoveTo/Undock hoàn thành theo chu kỳ NBR: true -> false -> true.</summary>
|
|
public Task WaitMoveTo(TimeSpan timeout, CancellationToken ct = default)
|
|
=> WaitNbrOnlyAsync(timeout, ct);
|
|
}
|
|
|
|
// ═══════════════════════════════════════════════════════════════
|
|
// VdaCommandAwaiter
|
|
// ═══════════════════════════════════════════════════════════════
|
|
|
|
/// <summary>
|
|
/// 3 cách check:
|
|
/// 1. .WaitAction(status) — chỉ ActionStates
|
|
/// 2. .WaitNbr() — chỉ NewBaseRequest
|
|
/// 3. .WaitEither(status) — chung cả 2, cái nào đến trước
|
|
/// </summary>
|
|
public class VdaCommandAwaiter
|
|
{
|
|
private readonly RobotConditionWaiter _watcher;
|
|
private readonly string _actionType;
|
|
|
|
internal VdaCommandAwaiter(RobotConditionWaiter watcher, string actionType)
|
|
{
|
|
_watcher = watcher;
|
|
_actionType = actionType;
|
|
}
|
|
|
|
// ── 1. Chỉ ActionStates ───────────────────────────────────────
|
|
|
|
/// <summary>Chỉ check ActionStates với status cụ thể. Throw nếu timeout.</summary>
|
|
public async Task WaitAction(VdaActionStatus status, TimeSpan timeout, CancellationToken ct = default)
|
|
{
|
|
var result = await _watcher.WaitActionOnlyAsync(_actionType, status.ToVdaString(), timeout, ct);
|
|
if (result.IsTimeout)
|
|
throw new TimeoutException(
|
|
$"[{_actionType}] không đạt '{status}' — {result.TimeoutSnapshot}");
|
|
}
|
|
|
|
// Shorthand properties — gõ . là ra ngay
|
|
public VdaStatusAwaiter Initializing => new(_watcher, _actionType, VdaActionStatus.Initializing);
|
|
public VdaStatusAwaiter Running => new(_watcher, _actionType, VdaActionStatus.Running);
|
|
public VdaStatusAwaiter Finished => new(_watcher, _actionType, VdaActionStatus.Finished);
|
|
public VdaStatusAwaiter Failed => new(_watcher, _actionType, VdaActionStatus.Failed);
|
|
public VdaStatusAwaiter Aborted => new(_watcher, _actionType, VdaActionStatus.Aborted);
|
|
|
|
// ── 2. Chỉ NewBaseRequest ─────────────────────────────────────
|
|
|
|
/// <summary>Chỉ check chu kỳ NewBaseRequest: phải thấy true -> false -> true.</summary>
|
|
public Task WaitNbr(TimeSpan timeout, CancellationToken ct = default)
|
|
=> _watcher.WaitNbrOnlyAsync(timeout, ct);
|
|
|
|
// ── 3. Chung cả 2 ─────────────────────────────────────────────
|
|
|
|
/// <summary>
|
|
/// Check ActionStates + NewBaseRequest — cái nào đến trước.
|
|
/// NewBaseRequest ưu tiên nếu cả 2 cùng lúc.
|
|
/// Throw nếu timeout.
|
|
/// Return VdaCompletionPath để caller biết path nào thắng nếu cần.
|
|
/// </summary>
|
|
public async Task<VdaCompletionPath> WaitEither(VdaActionStatus status, TimeSpan timeout, CancellationToken ct = default)
|
|
{
|
|
var result = await _watcher.WaitActionOrNbrAsync(
|
|
_actionType, [status.ToVdaString()], timeout, ct);
|
|
|
|
if (result.IsTimeout)
|
|
throw new TimeoutException(
|
|
$"[{_actionType}] WaitEither '{status}' — {result.TimeoutSnapshot}");
|
|
|
|
return result.Path;
|
|
}
|
|
|
|
/// <summary>WaitEither với terminal statuses (Finished/Failed/Aborted).
|
|
/// Throw RobotStateErrorException nếu action kết thúc bằng FAILED hoặc ABORTED.</summary>
|
|
public async Task<VdaCompletionPath> WaitEitherCompleted(TimeSpan timeout, CancellationToken ct = default)
|
|
{
|
|
var result = await _watcher.WaitActionOrNbrAsync(
|
|
_actionType,
|
|
[VdaActionStatus.Finished.ToVdaString(), VdaActionStatus.Failed.ToVdaString(), VdaActionStatus.Aborted.ToVdaString()],
|
|
timeout, ct);
|
|
|
|
if (result.IsTimeout)
|
|
throw new TimeoutException(
|
|
$"[{_actionType}] WaitEitherCompleted — {result.TimeoutSnapshot}");
|
|
|
|
if (result.IsAction && result.ActionStatus is "FAILED" or "ABORTED")
|
|
throw new RobotStateErrorException(
|
|
$"[{_actionType}] action kết thúc với trạng thái {result.ActionStatus}");
|
|
|
|
return result.Path;
|
|
}
|
|
}
|
|
|
|
// ═══════════════════════════════════════════════════════════════
|
|
// VdaStatusAwaiter — shorthand cho .Running.Wait() etc.
|
|
// ═══════════════════════════════════════════════════════════════
|
|
|
|
public class VdaStatusAwaiter
|
|
{
|
|
private readonly RobotConditionWaiter _watcher;
|
|
private readonly string _actionType;
|
|
private readonly VdaActionStatus _status;
|
|
|
|
internal VdaStatusAwaiter(RobotConditionWaiter watcher, string actionType, VdaActionStatus status)
|
|
{
|
|
_watcher = watcher;
|
|
_actionType = actionType;
|
|
_status = status;
|
|
}
|
|
|
|
/// <summary>Chỉ check ActionStates. Throw nếu timeout.</summary>
|
|
public async Task Wait(TimeSpan timeout, CancellationToken ct = default)
|
|
{
|
|
var result = await _watcher.WaitActionOnlyAsync(
|
|
_actionType, _status.ToVdaString(), timeout, ct);
|
|
if (result.IsTimeout)
|
|
throw new TimeoutException(
|
|
$"[{_actionType}] không đạt '{_status}' — {result.TimeoutSnapshot}");
|
|
}
|
|
}
|