using System;
using LaserWelder.Machine;
using LaserWelder.Util;
namespace LaserWelder.StateMachine
{
public class FSM : TaskLoop
{
private static FSM instance = new FSM();
public static FSM Instance => instance;
/// <summary>
/// 状态改变的事件 旧状态/新状态
/// </summary>
public event Action<StateType, StateType> RunStateChanged;
/// <summary>
/// 状态机当前的状态
/// </summary>
public StateBase CurrState { get; private set; }
/// <summary>
/// 状态机上一个状态
/// </summary>
public StateBase PreState { get; private set; }
/// <summary>
/// 焊接工作当前的状态
/// </summary>
public WeldWorkType CurrWelderState { get; set; }
public bool CanRequestPallet { get; set; }
public bool IsWorkEnd { get; set; }
public bool IsAutoRun => LaserWorkPrm.Instance.IsAutoRun;
public bool IsStop { get; private set; }
public bool IsPause { get; private set; }
private FSM()
{
}
/// <summary>
/// 已经Start后,点击此按钮无效
/// </summary>
public new void Start()
{
if (CurrState == null)
{
IsStop = false;
IsPause = false;
Delay = 1;
ChangeState(IdleState.Instance);
CanRequestPallet = true;
base.Start();//开启FSM update函数
}
}
public new void Stop()
{
base.Stop();
ChangeState(null);
CanRequestPallet = true;
IsStop = true;
//InnerAgency.Instance.Stop();
}
public void Pause()
{
IsPause = true;
}
public void Continue()
{
IsPause = false;
}
internal bool ChangeState(StateBase newState)
{
WorkEnd();
if (newState != null)
{
DebugMsg.SendMsg("ChangeState To " + newState.Type.ToString());
}
if (CurrState != null)
{
if (newState == null)
{
CurrState.Exit(StateType.Null);
RunStateChanged?.Invoke(CurrState.Type, StateType.Null);
}
else
{
CurrState.Exit(newState.Type);
RunStateChanged?.Invoke(CurrState.Type, newState.Type);
}
newState?.Enter(CurrState.Type);
}
else if (newState != null)
{
newState?.Enter(newState.Type);
RunStateChanged?.Invoke(StateType.Null, newState.Type);
}
PreState = CurrState;
CurrState = newState;
return true;
}
/// <summary>
/// 一片工作结束
/// </summary>
public void WorkEnd()
{
if (CurrState != null && CurrState == PalletOutState.Instance)
{
CurrState.WorkEnd();
}
}
protected override void Loop()
{
CurrState?.Update();
}
}
/// <summary>
/// 整机状态
/// </summary>
public enum StateType
{
Null,
Idle,
PalletIn,
PalletOut,
PalletUp,
PalletDown,
RequestPallet,
ReleasePallet,
Work,
Worked,
ShotMark,
Welding,
Running,
Pause,
Warning,
Alarming,
Stop
}
public static class StateTypeExt
{
public static string Msg(this StateType a)
{
return a.ToString();
}
}
}