StateMachine

StateMachine

Create State Machine

Create either a passive or an active state machine:

?
1
var fsm =
new
PassiveStateMachine<States, Events>()

?
1
var fsm =
new
ActiveStateMachine<States, Events>()

The above sample uses the enums States and Events that define the available states and events.

Define Transitions

A simple transition

?
1
2
fsm.In(States.A)
   
.On(Events.B).Goto(States.B);

If the state machine is in state A and receives event B then it performs a transition to state B.

Transition with action

?
1
2
3
4
fsm.In(States.A)
    
.On(Events.B)
        
.Goto(States.B)
        
.Execute(() => {
/* do something here */
});

Actions are defined with Execute. Multiple actions can be defined on a single transition. The actions are performed in the same order as they are defined. An action is defined as a delegate. Therefore, you can use lambda expressions or normal delegates. The following signatures are supported:

?
1
2
3
void
TransitionAction<T>(T parameter)
// to get access to argument passed to Fire
 
void
TransitionAction()
// for actions that do not need access to the argument passed to Fire

Actions can use the event argument that were passed to the Fire method of the state machine. If the type you specify as the generic parameter type does not match the argument passed with the event, an exception is thrown.

Transition with guard

?
1
2
3
4
fsm.In(States.A)
    
.On(Events.B)
        
.If(arguments =>
false
).Goto(States.B1)
        
.If(arguments =>
true
).Goto(States.B2);

Guards are used to decide which transition to take if there are multiple transitions defined for a single event on a state. Guards can use the event argument that was passed to the Fire method of the state machine. The first transition with a guard that returns true is taken.

The signature of guards is as follows:

?
1
2
3
bool
Guard<T>(T argument)
// to get access to the argument passed in Fire
 
bool
Guard()
// for guards that do not need access to the parameters passed to Fire

Entry and Exit Actions

?
1
2
3
fsm.In(States.A)
    
.ExecuteOnEntry(() => {
/* execute entry action stuff */
}
    
.ExecuteOnExit(() => {
/* execute exit action stuff */
};

When a transition is executed, the exit action of the current state is executed first. Then the transition action is executed. Finally, the entry action of the new current state is executed.

The signature of entry and exit actions are as follows:

?
1
void
EntryOrExitAction()

Internal and Self Transitions

Internal and Self transitions are transitions from a state to itself.

 

When an internal transition is performed then the state is not exited, i.e. no exit or entry action is performed. When an self transition is performed then the state is exited and re-entered, i.e. exit and entry actions, if any, are performed.

?
1
2
3
fsm.In(States.A)
    
.On(Events.Self).Goto(States.A)
// self transition
    
.On(Events.Internal)           
// internal transition

Define Hierarchies

The following sample defines that B1, B2 and B3 are sub states of state B. B1 is defined to be the initial sub state of state B.

?
1
2
3
4
5
fsm.DefineHierarchyOn(States.B)
    
.WithHistoryType(HistoryType.None)
    
.WithInitialSubState(States.B1)
    
.WithSubState(States.B2)
    
.WithSubState(States.B3);

History Types

When defining hierarchies then you can define which history type is used when a state is re-entered:

  • None:
    The state enters into its initial sub state. The sub state itself enters its initial sub state and so on until the innermost nested state is reached.
  • Deep:
    The state enters into its last active sub state. The sub state itself enters into its last active state and so on until the innermost nested state is reached.
  • Shallow:
    The state enters into its last active sub state. The sub state itself enters its initial sub state and so on until the innermost nested state is reached.

Initialize, Start and Stop State Machine

Once you have defined your state machine then you can start using it.

First you have to initialize the state machine to set the first state (A in the sample):

?
1
fsm.Initialize(States.A);

Afterward, you start the state machine:

?
1
fsm.Start();

Events are processed only if the state machine is started. However, you can queue up events before starting the state machine. As soon as you start the state machine, it will start performing the events.

To suspend event processing, you can stop the state machine:

?
1
fsm.Stop();

If you want, you can then start the state machine again, then stop it, start again and so on.

Fire Events

To get the state machine to do its work, you send events to it:

?
1
fsm.Fire(Events.B);

This fires the event B on the state machine and it will perform the corresponding transition for this event on its current state.

You can also pass an argument to the state machine that can be used by transition actions and guards:

?
1
fsm.Fire(Events.B, anArgument);

Another possibility is to send a priority event:

?
1
fsm.FirePriority(Events.B);

In this case, the event B is enqueued in front of all queued events. This is especially helpful in error scenarios to go to the error state immediately without performing any other already queued events first.

That’s it for the tutorial. See rest of documentation for more details on specific topics.

 

Sample State Machine

This is a sample state machine.

Definition

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
var elevator =
new
PassiveStateMachine<States, Events>(
"Elevator"
);
 
elevator.DefineHierarchyOn(States.Healthy)
    
.WithHistoryType(HistoryType.Deep)
    
.WithInitialSubState(States.OnFloor)
    
.WithSubState(States.Moving);
elevator.DefineHierarchyOn(States.Moving)
    
.WithHistoryType(HistoryType.Shallow)
    
.WithInitialSubState(States.MovingUp)
    
.WithSubState(States.MovingDown);
elevator.DefineHierarchyOn(States.OnFloor)
    
.WithHistoryType(HistoryType.None)
    
.WithInitialSubState(States.DoorClosed)
    
.WithSubState(States.DoorOpen);
 
elevator.In(States.Healthy)
    
.On(Events.ErrorOccured).Goto(States.Error);
 
elevator.In(States.Error)
    
.On(Events.Reset).Goto(States.Healthy)
    
.On(Events.ErrorOccured);
 
elevator.In(States.OnFloor)
    
.ExecuteOnEntry(
this
.AnnounceFloor)
    
.ExecuteOnExit(Beep)
    
.ExecuteOnExit(Beep)
// just beep a second time
    
.On(Events.CloseDoor).Goto(States.DoorClosed)
    
.On(Events.OpenDoor).Goto(States.DoorOpen)
    
.On(Events.GoUp)
        
.If(CheckOverload).Goto(States.MovingUp)
        
.Otherwise().Execute(
this
.AnnounceOverload, Beep)
    
.On(Events.GoDown)
        
.If(CheckOverload).Goto(States.MovingDown)
        
.Otherwise().Execute(
this
.AnnounceOverload);
 
elevator.In(States.Moving)
    
.On(Events.Stop).Goto(States.OnFloor);
 
elevator.Initialize(States.OnFloor);

The above state machine uses these actions and guards:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
private
void
AnnounceFloor()
{
    
/* announce floor number */
}
 
private
void
AnnounceOverload()
{
    
/* announce overload */
}
 
private
void
Beep()
{
    
/* beep */
}
 
private
bool
CheckOverload()
{
    
return
whetherElevatorHasOverload;
}

Run the State Machine

This is a small sample to show how to interact with the state machine:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
// queue some events to be performed when state machine is started.
elevator.Fire(Events.ErrorOccured);
elevator.Fire(Events.Reset);
             
elevator.Start();
 
// these events are performed immediately
elevator.Fire(Events.OpenDoor);
elevator.Fire(Events.CloseDoor);
elevator.Fire(Events.GoUp);
elevator.Fire(Events.Stop);
elevator.Fire(Events.OpenDoor);
 
elevator.Stop();

Log

If you add the log4net log extensions available in the Appccelerate.SourceTemplate package:

?
1
elevator.AddExtension(
new
Appccelerate.Log4Net.StateMachineLogExtension<States, Events>(
"Elevator"
));

to the above code then these are the log messages (if all are enabled – see log4net documentation on how to configure log messages). Note how the state exits and enters are logged, especially for hierarchical transitions.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Logger      Level   Message
Elevator    INFO    State machine Elevator initializes to state OnFloor.
Elevator    INFO    State machine Elevator switched from state  to state DoorClosed.
Elevator    DEBUG    State machine Elevator performed  -> Enter Healthy -> Enter OnFloor -> Enter DoorClosed.
Elevator    INFO    Fire
event
ErrorOccured on state machine Elevator with current state DoorClosed and
event
arguments .
Elevator    INFO    State machine Elevator switched from state DoorClosed to state Error.
Elevator    DEBUG    State machine Elevator performed  -> Exit DoorClosed -> Exit OnFloor -> Exit Healthy -> Enter Error.
Elevator    INFO    Fire
event
Reset on state machine Elevator with current state Error and
event
arguments .
Elevator    INFO    State machine Elevator switched from state Error to state DoorClosed.
Elevator    DEBUG    State machine Elevator performed  -> Exit Error -> Enter Healthy -> Enter OnFloor -> Enter DoorClosed.
Elevator    INFO    Fire
event
OpenDoor on state machine Elevator with current state DoorClosed and
event
arguments .
Elevator    INFO    State machine Elevator switched from state DoorClosed to state DoorOpen.
Elevator    DEBUG    State machine Elevator performed  -> Exit DoorClosed -> Enter DoorOpen.
Elevator    INFO    Fire
event
CloseDoor on state machine Elevator with current state DoorOpen and
event
arguments .
Elevator    INFO    State machine Elevator switched from state DoorOpen to state DoorClosed.
Elevator    DEBUG    State machine Elevator performed  -> Exit DoorOpen -> Enter DoorClosed.
Elevator    INFO    Fire
event
GoUp on state machine Elevator with current state DoorClosed and
event
arguments .
Elevator    INFO    State machine Elevator switched from state DoorClosed to state MovingUp.
Elevator    DEBUG    State machine Elevator performed  -> Exit DoorClosed -> Exit OnFloor -> Enter Moving -> Enter MovingUp.
Elevator    INFO    Fire
event
Stop on state machine Elevator with current state MovingUp and
event
arguments .
Elevator    INFO    State machine Elevator switched from state MovingUp to state DoorClosed.
Elevator    DEBUG    State machine Elevator performed  -> Exit MovingUp -> Exit Moving -> Enter OnFloor -> Enter DoorClosed.
Elevator    INFO    Fire
event
OpenDoor on state machine Elevator with current state DoorClosed and
event
arguments .
Elevator    INFO    State machine Elevator switched from state DoorClosed to state DoorOpen.
Elevator    DEBUG    State machine Elevator performed  -> Exit DoorClosed -> Enter DoorOpen.

You can write your own extension for different logging.

Reports

yEd Report

sample yEd report

csv Report

Source Entry Exit Children
OnFloor AnnounceFloor Beep, Beep DoorClosed, DoorOpen
Moving     MovingUp, MovingDown
Healthy     OnFloor, Moving
MovingUp      
MovingDown      
DoorClosed      
DoorOpen      
Error      
Source Event Guard Target Actions
OnFloor CloseDoor   DoorClosed  
OnFloor OpenDoor   DoorOpen  
OnFloor GoUp CheckOverload MovingUp  
OnFloor GoUp   internal transition AnnounceOverload, Beep
OnFloor GoDown CheckOverload MovingDown  
OnFloor GoDown   internal transition AnnounceOverload
Moving Stop   OnFloor  
Healthy ErrorOccured   Error  
Error Reset   Healthy  
Error ErrorOccured   internal transition  

Textual Report

Elevator: initial state = OnFloor
    Healthy: initial state = OnFloor history type = Deep
        entry action: 
        exit action: 
        ErrorOccured -> Error actions:  guard: 
        OnFloor: initial state = DoorClosed history type = None
            entry action: AnnounceFloor
            exit action: Beep, Beep
            CloseDoor -> DoorClosed actions:  guard: 
            OpenDoor -> DoorOpen actions:  guard: 
            GoUp -> MovingUp actions:  guard: CheckOverload
            GoUp -> internal actions: AnnounceOverload, Beep guard: 
            GoDown -> MovingDown actions:  guard: CheckOverload
            GoDown -> internal actions: AnnounceOverload guard: 
            DoorClosed: initial state = None history type = None
                entry action: 
                exit action: 
            DoorOpen: initial state = None history type = None
                entry action: 
                exit action: 
        Moving: initial state = MovingUp history type = Shallow
            entry action: 
            exit action: 
            Stop -> OnFloor actions:  guard: 
            MovingUp: initial state = None history type = None
                entry action: 
                exit action: 
            MovingDown: initial state = None history type = None
                entry action: 
                exit action: 
    Error: initial state = None history type = None
        entry action: 
        exit action: 
        Reset -> Healthy actions:  guard: 
        ErrorOccured -> internal actions:  guard: 
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/109243.html原文链接:https://javaforall.net

(1)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 常见函数的定义域_函数定义域的求解

    常见函数的定义域_函数定义域的求解——————————————————————————————————————————————————————————————————…

    2025年7月21日
    5
  • 电平转换芯片_电平转换芯片无方向

    电平转换芯片_电平转换芯片无方向电平转换芯片**在混合信号系统中,经常能看到电瓶转换电路,目前市面上应用较多的处理器都是采用3.3V电源供电,但是产品外围器件多数都采用5伏电源供电,这种情况下就必须使用转换电路。目前应用比较多的两类电平转换电路是用MOS管搭建的电平转换电路,和用电平转换芯片实现的电路。为了降低产品的功耗,通常都采用低工作电压值的高速逻辑器件,这也进一步导致了产品内部同时存在多种电压,因此搭建稳定可靠的电平转换电路,尤为重要。如要求低成本,可以用MOSFET管自己搭建一个电平转换电路。用MOSFET管搭建电平转换电

    2022年8月10日
    6
  • 数据建模方法及步骤图_comsol建模步骤教程

    数据建模方法及步骤图_comsol建模步骤教程何为建模?数据几乎总是用于两种目的:操作型记录的保存和分析型决策的制定。简单来说,操作型系统保存数据,分型型系统使用数据。前者一般仅反映数据的最新状态,按单条记录事务性来处理;其优化的核心是更快地处理事务。后者往往是反映数据一段时间的状态变化,按大批量方式处理数据;其核心是高性能、多维度处理数据。通常我们将操作型系统简称为OLTP(On-LineTransactionProcessing)…

    2022年9月16日
    3
  • mse均方误差计算公式推导_误差函数erf是怎么算出来的

    mse均方误差计算公式推导_误差函数erf是怎么算出来的 

    2022年9月30日
    0
  • python 和 java 到底该学哪个?

    python 和 java 到底该学哪个?随着互联网的高速发展,越来越多的人选择加入到IT行业,而近年来,编程语言界也可以说是百花齐放……那么,对于刚入行的小伙伴来讲,到底选择哪种编程语言学习更好呢?是一直独占鳌头的Java,还是后来居上的Python,或者近两年一直很热门的大数据、人工智能呢?在做选择前,我们首先要现有个概念认知,就是Java、Python和所谓大数据、人工智能,并不是一个同类。Java、Python是计算机的编程语…

    2022年7月7日
    32
  • Apache的URL地址重写(RewriteCond与RewriteRule)

    Apache的URL地址重写(RewriteCond与RewriteRule)Apache的URL地址重写http://hi.baidu.com/sonan/blog/item/c408963d89468208bba16716.html第一种方法:Apache环境中如果要将URL地址重写,正则表达式是最基本的要求,但对于一般的URL地址来说,基本的匹配就能实现我们大部分要求,因此除非是非常特殊的URL地址,但这不是我要讨论的范围,简单几招学会Apache中URL地

    2022年6月11日
    24

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号