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 Firevoid 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 Firebool 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 immediatelyelevator.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 MessageElevator 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

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:
StateMachine的更多相关文章
- Quick StateMachine状态机
状态机quick中是一个亮点,假设我们做一款RPG游戏,一个角色通常会拥有idle,attack,walk.run,death这些状态,假设游戏角色的状态採用分支条件推断的话.会造成很庞大而难以维护. ...
- mina statemachine解读(二)
这里主要讲下对外接口暴露的处理. // 创建对外接口对象 TaskWork taskWork = new StateMachineProxyBuilder().setStateContextLooku ...
- mina statemachine解读(一)
statemachine(状态机)在维护多状态数据时有非常好的作用,现在github上star排名最前的是squirrel-foundation以及spring-statemachine,而min ...
- Copycat - StateMachine
看下用户注册StateMachine的过程, CopycatServer.Builder builder = CopycatServer.builder(address); builder.withS ...
- Spring Boot 揭秘与实战(七) 实用技术篇 - StateMachine 状态机机制
文章目录 1. 环境依赖 2. 状态和事件 2.1. 状态枚举 2.2. 事件枚举 3. 状态机配置4. 状态监听器 3.1. 初始化状态机状态 3.2. 初始化状态迁移事件 5. 总结 6. 源代码 ...
- Spring Boot - StateMachine状态机
是Spring Boot提供的状态机的现成实现. 理论(有点像工作流) 需要定义一些状态的枚举,以及一些引起状态变化的事件的枚举. 每个状态可以对应的创建一个继承自org.springframewor ...
- quick 状态机StateMachine
function Player:addStateMachine() self.fsm_ = {} cc.GameObject.extend(self.fsm_) :addComponent(" ...
- Android stateMachine分析
StateMachine与State模式的详细介绍可以参考文章:Android学习 StateMachine与State模式 下面是我对于StateMachine的理解: 先了解下消息处理.看下Sta ...
- stateMachine 相关知识
一个state的基本构造,processMessage 以及可选的enter exit 和getName. processMessager是用于处理数据. enter 和exit 则是类似于 面向编程 ...
- Spring Boot 2.x实战之StateMachine
本文首发于个人网站:Spring Boot 2.x实战之StateMachine Spring StateMachine是一个状态机框架,在Spring框架项目中,开发者可以通过简单的配置就能获得一个 ...
随机推荐
- Unity3D研究院之Inspector面板枚举的别名与排序
虽然mono是支持unicode的.可以在枚举里写中文,但是我还是觉得写英文好一些.可是在编辑器上策划是希望看到的是中文的,还有就是枚举的展示排序功能,策划在编辑的时候为了方便希望把常用的枚举排上前面 ...
- WCF Data Service 使用小结 —— 了解OData(一)
最近做了一个小项目,其中用到了 WCF Data Service,之前是叫 ADO.NET Data Service 的.关于WCF Data Service,博客园里的介绍并不多,但它确实是个很好的 ...
- 斐波那契数列PHP非递归数组实现
概念: 斐波那契数列即表达式为 a(n) = a(n-1)+a(n-2) 其中 a1 =0 a2 = 1 的数列 代码实现功能: 该类实现初始化给出n,通过调用getValue函数得出a(n)的值 ...
- EDIUS删除创建的工程预设的教程
自从第一次启动EDIUS 8,创建了一个工程预设,之后每次启动软件都会出现,但创建的预设又用不着了,如何删除呢?下面,小编就 给大家演示如何正确删除EDIUS 8工程预设. 1.启动软件,点击设置菜单 ...
- svg如何用marker 定义一个黑色的小圆点
<defs> <marker id="markerStartArrow" viewBox="0 0 30 30" refX="10& ...
- OpenJudge计算概论-点和正方形的关系【判断点是否在正方形内部】
/*======================================================== 点和正方形的关系 总时间限制: 1000ms 内存限制: 65536kB 描述 有 ...
- .htaccess中301强制跳转到带www前缀或不带www的域名
相信很多站长朋友都有这样的的问题出现.即带www前缀的域名与不带www前缀的顶级域名收录情况是不同的.这个问题主要是由于搜索引擎对于顶级域名与二级域名权重判定不同造成的.毫无疑问地,唯一的域名能够给你 ...
- datatables的Bootstrap样式的分页怎么添加首页和尾页(引)
找到dataTables.bootstrap.js(版本3):(此项目中文件名为:dataTableExt.js) $.fn.dataTableExt.oApi.fnPagingInfo = func ...
- VMware虚拟系统 bridged、NAT、host-only三种网络连接模式
目录 前言 bridged(桥接模式) NAT(网络地址转换模式) host-only(仅主机模式) 总结 前言 如果你想利用VMWare安装虚拟机,或想创建一个与网内其他机器相隔离的虚拟系统,进行特 ...
- Android中实现java与PHP服务器(基于新浪云免费云平台)http通信详解
Android中实现java与PHP服务器(基于新浪云免费云平台)http通信详解 (本文转自: http://blog.csdn.net/yinhaide/article/details/44756 ...