Add project files.
This commit is contained in:
@@ -0,0 +1,94 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SafeBagDE70.StateMachine
|
||||
{
|
||||
public class ProcessStateMachine
|
||||
{
|
||||
private string? _currentState;
|
||||
|
||||
public ProcessStateMachine()
|
||||
{
|
||||
_currentState = App.StateMachineConfig.States.FirstOrDefault();
|
||||
}
|
||||
|
||||
public string CurrentState => _currentState;
|
||||
|
||||
public bool CanTransitionTo(string newState, out Transition transition)
|
||||
{
|
||||
transition = App.StateMachineConfig.Transitions
|
||||
.FirstOrDefault(t => t.From.Contains(_currentState) && t.To.Contains(newState));
|
||||
|
||||
return transition != null;
|
||||
}
|
||||
|
||||
public void TransitionToState(string newState)
|
||||
{
|
||||
if (CanTransitionTo(newState, out Transition transition))
|
||||
{
|
||||
if (ExecuteActions(transition))
|
||||
{
|
||||
// Transition to the new state if the required condition is met
|
||||
_currentState = newState;
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"Failed to meet action requirements. Staying in {_currentState}.");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
throw new InvalidOperationException($"Cannot transition from {_currentState} to {newState}");
|
||||
}
|
||||
}
|
||||
|
||||
private bool ExecuteActions(Transition transition)
|
||||
{
|
||||
bool allRequiredActionsSucceeded = true;
|
||||
bool atLeastOneActionSucceeded = false;
|
||||
|
||||
foreach (var action in transition.Actions)
|
||||
{
|
||||
bool success = ExecuteAction(action.Name);
|
||||
|
||||
if (success)
|
||||
{
|
||||
atLeastOneActionSucceeded = true;
|
||||
}
|
||||
|
||||
if (action.IsRequired && !success)
|
||||
{
|
||||
allRequiredActionsSucceeded = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Determine if the transition should happen based on the condition
|
||||
if (transition.RequireAtLeastOneActionSuccess)
|
||||
{
|
||||
return atLeastOneActionSucceeded;
|
||||
}
|
||||
else
|
||||
{
|
||||
return allRequiredActionsSucceeded;
|
||||
}
|
||||
}
|
||||
|
||||
private bool ExecuteAction(string actionName)
|
||||
{
|
||||
// Simulate action execution based on the action name
|
||||
//Console.WriteLine($"Executing action: {App.StateMachineConfig.Actions[actionName]}");
|
||||
switch(actionName)
|
||||
{
|
||||
case "DoInit":
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
// For the sake of this example, all actions succeed
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user