Introduction
We have used SMC for many years. When we tried it again, it had no specific support for Kotlin. We did not create a code generator for Kotlin. Instead, we made a Kotlin DSL and a simple implementation.
To learn more about finite state machines, see:
The Tutorial has examples that show how to write a state machine definition with the DSL.
Features
kfsm has these features:
-
Event-driven state machine.
-
External transitions and internal transitions.
-
Entry actions and exit actions for each state.
-
Default actions for each state.
-
Default entry actions and default exit actions.
-
A query for the events that the current state or a given state allows.
-
Multiple state maps with push transitions and pop transitions.
-
Automatic transitions.
-
Externalized state.
-
Simple visualization.
-
Detailed visualization.
-
Visualization Gradle plugin.
-
Coroutines.
-
Timeout transitions.
-
State change notification action.
Getting Started
Repository
Releases are on Maven Central. Snapshots are in the GitHub Packages Maven repository. Contact us for a personal access token (PAT) to get snapshot releases.
Dependencies
Kotlin Multiplatform (build.gradle.kts)
repositories {
mavenCentral()
}
kotlin {
sourceSets {
commonMain.dependencies {
implementation("org.infosmid:kfsm:2.0.0")
}
}
}
Kotlin Multiplatform (build.gradle - Groovy DSL)
repositories {
mavenCentral()
}
kotlin {
sourceSets {
commonMain {
dependencies {
implementation 'org.infosmid:kfsm:2.0.0'
}
}
}
}
Single Platform (JVM / Android)
Kotlin DSL (build.gradle.kts)
repositories {
mavenCentral()
}
dependencies {
implementation("org.infosmid:kfsm:2.0.0")
}
Groovy DSL (build.gradle)
repositories {
mavenCentral()
}
dependencies {
implementation 'org.infosmid:kfsm:2.0.0'
}
Gradle version catalog (gradle/libs.versions.toml)
Declare the library in the version catalog:
[versions]
kfsm = "2.0.0"
[libraries]
infosmid-kfsm = { module = "org.infosmid:kfsm", version.ref = "kfsm" }
Then use the catalog accessor in the build script.
For Kotlin Multiplatform
Kotlin Multiplatform
repositories {
mavenCentral()
}
kotlin {
sourceSets {
commonMain {
dependencies {
implementation(libs.infosmid.kfsm)
}
}
}
}
For a single platform (JVM / Android)
Single Platform
repositories {
mavenCentral()
}
dependencies {
implementation(libs.infosmid.kfsm)
}
Finite State Machines
This section describes the life cycle and the design of kfsm.
Terms
Some terms have a specific meaning in kfsm. Use this list to avoid confusion with other meanings of the same words.
- State machine
-
The object that processes events. In this document, state machine means a state machine that you define with kfsm.
FSMis the short form that code and diagrams use. - State (
S) -
A value that describes the situation of the context. A state can be any value that has
equalsandhashCode. Most examples use anenum class. - Event (
E) -
A value that you send to the state machine. An event can cause a transition. Like a state, an event is any value that has
equalsandhashCode. - Argument (
A) -
A value that you send together with an event. All events of one state machine have the same argument type. This is not a Kotlin function argument.
- Return value (
R) -
The value that
sendEventreturns. It is the result of the action that ran. - Context (
C) -
The object that the actions operate on. The action lambdas use the context as
this. This is not aCoroutineContext. - Action
-
A lambda that the state machine runs during a transition. An action is not a user interface action or an event.
- Transition
-
The change that an event causes. A transition can run actions and can change the state.
- External transition
-
A transition that has a target state. The state machine runs the exit action and the entry action. This is true also when the target state is the same as the current state.
- Internal transition
-
A transition that has no target state. The state stays the same. The state machine does not run the exit action or the entry action.
- Guard expression
-
A lambda that returns a
Boolean. A transition that has a guard expression occurs only when the guard returnstrue. - Entry action and exit action
-
Actions that run for an external transition. The exit action runs for the current state. The entry action runs for the target state.
- Default action
-
An action that runs when no transition matches the current state and the event. This is not the default value of a Kotlin parameter.
- State map
-
A group of states with their transitions and actions. This is not a Kotlin
Map. A state machine has one top-level state map and can have named state maps. - Default state map
-
The top-level state map. Its name is
default. - Push transition and pop transition
-
Transitions that change the current state map. A push transition puts the current state map on a stack and makes a named state map current. A pop transition removes the current state map from the stack. The previous state map becomes current.
- Automatic transition
-
A transition that has no event. The state machine selects it after another transition completes.
- Timeout transition
-
A transition that has no event. It occurs when a configured time expires after the state machine enters the state. Only asynchronous state machines have timeout transitions.
- Definition
-
The immutable description of a state machine. You can share one definition.
- Instance
-
A state machine that you create from a definition. An instance has a context and a current state.
- Externalized state
-
A list of pairs of a state and a state map name. You can store it and use it to create an instance later.
- Invariant
-
A condition that must be
truebefore and after every transition.
Definition
You define a state machine with a DSL, as this document describes.
In the definition, you describe:
-
The types of the states and the events.
-
The behavior of the state machine for each event.
-
How the actions operate on the context.
State types and event types must be value types.
They must have equals and hashCode.
An enum class is a good choice, but it is not necessary.
When kfsm-viz creates a state diagram, it uses the states START and END as the start state and the end state.
An event can have an argument and can return a value. The argument type is the same for all events. To send different types of arguments, use a sealed class as the argument type.
A state machine has one or more state maps. Each state map has a subset of the states.
The definition lists the events of the state machine.
The state machine applies actions to a context. The context represents the work that the state machine does.
An event can cause a transition. A transition defines the actions that the state machine runs when it is in a specific state.
A transition can have a guard expression.
The transition occurs only when the guard returns true.
An automatic transition belongs to a state and has no event. The state machine selects an automatic transition after another transition completes and the state is the current state.
A timeout transition belongs to a state.
It occurs when a configured time expires after the state machine enters the state.
If the transition has a guard expression, the guard must return true.
Instance
You create an instance from a definition. You give the instance a context. You can also give it an externalized state. The definition can also derive the current state from the context.
You send events to the instance. If the event needs an argument, you send it together with the event. An event can cause the state machine to run actions.
You can ask the instance which events the current state allows. You can also ask for the events of a given state. Use this to disable controls in a user interface. A back-end application that uses HATEOAS can use it to add only the links for allowed events.
If a state machine has timeout transitions, the instance must stay active. This is usually necessary only in user interface applications and in embedded interactive applications.
In a stateless environment, requests or events drive the application. If the state is not derived from the context, externalize the state after you use the instance. The externalized state is a list of pairs. Each pair has a state and the name of its state map.
Initial State
An instance needs an initial state. The state machine uses the first of these that is available:
-
The externalized state that you give to
create. -
The
initialStatesexpression. -
The initial state that you give to
create. -
The
initialStateexpression. -
The
defaultInitialState.
If none is available, create throws an exception.
Named Maps and Push / Pop Transitions
A named state map is a group of states. A push transition goes to a named state map. A pop transition returns from it.
A push transition needs:
-
The name of the target state map.
-
The target state.
-
The event, as for a normal transition.
-
Optionally, a guard expression and an action.
When a push transition occurs, the state machine puts the current state map on a stack. Then it creates an instance of the named state map. This instance becomes the current state map. The state machine processes events with the transition rules of the current state map.
A pop transition removes the current state map from the stack. The previous state map becomes the current state map. If the pop transition has a target state, the state of the previous state map changes to the target state. If the pop transition has a target map, a push transition follows.
DSL
The DSL is the way to configure a state machine. It supports:
-
Internal transitions and external transitions.
-
A transition is external when it has a target state, also when the target state is the same as the current state.
-
-
Guard expressions.
-
Entry actions and exit actions for each state and for all states.
-
Default actions for each state and for all states.
-
Named state maps.
-
Push transitions and pop transitions.
-
Automatic transitions.
-
Timeout transitions.
-
Actions that are
suspendfunctions. -
An invariant. The state machine checks the invariant for all events. If the invariant is not
true, it throws anInvariantException.
All configuration calls are applied to StateMachineBuilder.
stateMachine
The top-level element is stateMachine.
Use one of these functions:
Two more overloads of stateMachine use Any as the return type and as the argument type.
Use them when the state machine does not use the argument or the return value.
// using global function
val definition = stateMachine(
State.values().toSet(),
Event.values().toSet(),
ContextType::class,
ArgType::class,
ReturnType::class
) {
defaultInitialState = State.S1 // optional start state
invariant { } // invariant for stateMachine
default { // global defaults
}
initialState { // initial state expression
}
initialStates { // define expression for deriving state stack for nested maps.
}
onStateChange { // define an event handler to be invoked after a transition when the state has changed.
}
stateMap { // define named statemap
}
whenState { // state definition
}
}.build()
functionalStateMachine
The top-level element is functionalStateMachine.
Use this function:
It is the same as stateMachine, but the context type, the argument type and the return type are the same type.
Use it with an immutable context.
// using global function
val definition = functionalStateMachine(
State.values().toSet(),
Event.values().toSet(),
ContextType::class
) {
defaultInitialState = State.S1 // optional start state
invariant { } // invariant for stateMachine
default { // global defaults
}
initialState { // initial state expression
}
initialStates { // define expression for deriving state stack for nested maps.
}
onStateChange { // define an event handler to be invoked after a transition when the state has changed.
}
stateMap { // define named statemap
}
whenState { // state definition
}
}.build()
asyncStateMachine
Use asyncStateMachine to create a definition where the actions are suspend functions.
It also adds the timeout transitions to the state map handlers.
To create an instance from the definition, give it a CoroutineScope.
Two more overloads of asyncStateMachine use Any as the return type and as the argument type.
Use them when the state machine does not use the argument or the return value.
// using global function
val definition = asyncStateMachine(
State.values().toSet(),
Event.values().toSet(),
ContextType::class,
ArgType::class,
ReturnType::class
) {
defaultInitialState = State.S1 // optional
invariant { } // invariant for stateMachine
default { // global defaults
}
initialState { // initial state expression
}
initialStates { // define expression for deriving state stack for nested maps.
}
onStateChange { // define an event handler to be invoked after a transition when the state has changed.
}
stateMap { // define named statemap
}
whenState { // state definition
}
}.build()
asyncFunctionalStateMachine
asyncFunctionalStateMachine is the same as asyncStateMachine, but the context type, the argument type and the return type are the same type.
// using global function
val definition = asyncFunctionalStateMachine(
State.values().toSet(),
Event.values().toSet(),
ContextType::class
) {
defaultInitialState = State.S1 // optional
invariant { } // invariant for stateMachine
default { // global defaults
}
initialState { // initial state expression
}
initialStates { // define expression for deriving state stack for nested maps.
}
onStateChange { // define an event handler to be invoked after a transition when the state has changed.
}
stateMap { // define named statemap
}
whenState { // state definition
}
}.build()
default
-
Handler: DslStateMachineHandler::default
-
Mandatory: Optional
-
Cardinality: Multiple
Use default to configure the entry action, the exit action and the action for all states.
Example:
default {
action { // global action
}
onEntry { // global state entry action
}
onExit { // global state exit action
}
onEvent { // default transitions
}
}
action
-
Mandatory: Optional
-
Cardinality: Single
Give a lambda of type C.(S, E, A?) → R?.
The state machine runs it when no other transition matches.
Example:
action { currentState, event, arg -> // global default action
contextFunction()
anotherContextFunction()
}
onEntry
-
Mandatory: Optional
-
Cardinality: Single
Give a lambda of type C.(S, S, A?) → Unit.
The state machine runs it for each external transition, before the state changes.
The state machine runs the global entry action after the entry action of the state.
Example:
onEntry { fromState, targetState, arg ->
entryAction()
}
onExit
-
Mandatory: Optional
-
Cardinality: Single
Give a lambda of type C.(S, S, A?) → Unit.
The state machine runs it for each external transition, before the state changes.
The state machine runs the global exit action after the exit action of the state.
Example:
onExit { fromState, targetState, arg ->
exitAction()
}
onEvent
-
Arguments:
(event: E [to targetState: S]) -
Mandatory: Optional
-
Cardinality: Multiple
Use onEvent to define a transition for an event when no other transition matches.
There are two variations.
The first variation is an internal transition and has no target state.
The second variation is an external transition and has a target state.
In both variations, the lambda type is C.(A?) → R?.
Example:
onEvent(Event.EVENT) { arg -> // default internal state action for given event
someFunction()
}
onEvent(Event.EVENT to State.STATE) { arg -> // default external state action for given event
anotherFunction()
}
initialState
-
Handler: DslStateMachineHandler::initialState
-
Mandatory: Optional
-
Cardinality: Single
Give a lambda of type C.() → S.
The lambda derives the state of the state machine from the context.
Example:
initialState {
when(flag) {
1 -> State.S1
2 -> State.S2
else -> error("Invalid state")
}
}
initialStates
-
Mandatory: Optional
-
Cardinality: Single
If the state machine has named state maps, you must use initialStates.
You cannot use initialState with named state maps.
Give a lambda of type C.() → StateMapList<S>.
The lambda derives the state map stack from the context.
It returns a list of pairs of a state and a state map name.
The first pair is the bottom of the stack.
The last pair is the current state map.
Example:
initialStates {
mutableListOf<StateMapItem<PayingTurnstileStates>>().apply {
if (locked) {
this.add(PayingTurnstileStates.LOCKED to "default")
} else {
this.add(PayingTurnstileStates.UNLOCKED to "default")
}
if (coins > 0) {
this.add(PayingTurnstileStates.COINS to "coins")
}
}.toMap()
}
onStateChange
-
Mandatory: Optional
-
Cardinality: Single
Give a lambda of type C.(S, S) → Unit.
The first argument is the previous state.
The second argument is the new state.
The state machine runs this lambda after a transition completes and the new state is in effect. It does not run the lambda when the state stays the same. The exit actions and the entry actions run before the state changes. Inside these actions, a check of the allowed events still shows the previous state.
The state machine catches an exception from the lambda. It does not throw the exception again.
whenState
-
Arguments:
(currentState: S) -
Handler: DslStateMachineHandler::whenState
-
Mandatory: Mandatory
-
Cardinality: Multiple
Each whenState block describes the transitions for one state.
Example:
whenState(State.STATE) {
default { // default action for State.STATE
}
onEntry { // entry action for State.STATE
}
onExit { // exit action for State.STATE
}
onEvent(Event.EV2 to State.S1, guard = {flag == 1 }) { // external transition with guard expression
}
onEventPush(Event.EV2, "mapName", State.S1, guard = { flag == 1}) { // push transition to new map with guard expression
}
onEventPop(Event.EV3, "newMap", State.S3) { // pop transition leading into new push transition while executing current action only
}
automatic(State.S1, guard = { flag == 1}) { // automatic transition to new state when guard is met
}
// timeout is limited to AsyncStateMachineBuilder
timeout(State.S1, timeout, [guard = { expression }]) { // transition to S1 when timeout is triggered and guard is true
}
timeoutPop(State.S1, timeout, [guard = { expression }]) { // pop transition to S1 when timeout is triggered and guard is true
}
timeoutPush(State.S1, "mapName", timeout, [guard = { expression }]) { // push transition to S1 in "mapName" when timeout is triggered and guard is true
}
}
default
-
Handler: DslStateMachineEventHandler::default
-
Mandatory: Optional
-
Cardinality: Single
A state block can have one default action.
It is a lambda of type C.(S, E, A?) → R?.
The state machine runs it when no transition matches the state, the event and the guard expressions.
Example:
default { fromState, event, arg -> // default state action
someDefaultAction()
}
onEntry
-
Handler: DslStateMachineEventHandler::onEntry
-
Mandatory: Optional
-
Cardinality: Single
Give a lambda of type C.(S, S, A?) → Unit.
The state machine runs it for an external transition that has this state as the target state.
It runs after the transition action.
Example:
onEntry { fromState, targetState, arg -> // state entry action
println("Entering:$targetState from $fromState with $arg")
}
onExit
-
Handler: DslStateMachineEventHandler::onExit
-
Mandatory: Optional
-
Cardinality: Single
Give a lambda of type C.(S, S, A?) → Unit.
The state machine runs it for an external transition that starts in this state.
It runs before the transition action.
Example:
onExit { fromState, targetState, arg -> // state exit action
println("Exiting:$fromState to $targetState with $arg")
}
automatic
-
Arguments:
(targetState: S [, guard:{}]) -
Mandatory: Optional
-
Cardinality: Multiple
There are two variations of the automatic transition. One variation has a guard expression. The other variation has no guard expression.
The state machine selects an automatic transition after it completes a transition, when this state is the current state.
It selects the transition in the same way as for an event.
The first guard that returns true selects the transition.
If no guard returns true, the state machine uses the transition that has no guard.
Example:
whenState(State.S1) {
automatic(State.S1, guard = { flag == 1}) { // automatic transition to new state when guard is met
}
automatic(State.S1) { // automatic transition to new state
}
}
automaticPop
-
Arguments:
([targetMap: String,][,targetState: S] [, guard:{}]) -
Mandatory: Optional
-
Cardinality: Multiple
There are six variations of the automatic pop transition. Each variation has or does not have a guard expression. Each variation has no target, a target state, or a target map and a target state. If the transition has a target map, a push transition follows the pop transition.
Example:
whenState(State.S1) {
automaticPop { // pop when S1
}
automaticPop(guard= { flag == 1 }) { // pop when S1 and guard is true
}
automaticPop(State.S2, guard = { flag == 1 }) { // automatic pop transition to new state when guard is met
}
automaticPop(State.S2) { // automatic pop transition to new state
}
automaticPop("map1", State.S2) { // automatic pop transition to push transition to new state in target map
}
automaticPop("map1", State.S2, guard={flag == 1 }) { // automatic pop transition to push transition to new state in target map
}
}
automaticPush
-
Arguments:
(targetMap: String, targetState: S [, guard:{}]) -
Mandatory: Optional
-
Cardinality: Multiple
There are two variations of the automatic push transition. One variation has a guard expression. The other variation has no guard expression.
Example:
whenState(State.S1) {
automaticPush("map1", State.S2) { // automatic push transition to S2 in target map "map1"
}
automaticPush("map1", State.S2, guard={flag == 1 }) { // automatic push transition to S2 in target map "map1" if guard is true
}
}
onEvent
-
Arguments:
(event: E [to targetState: S],[guard: {}]) -
Handler: DslStateMachineEventHandler::onEvent
-
Mandatory: Optional
-
Cardinality: Multiple
There are four variations of the transition. A transition is external or internal. It has or does not have a guard expression.
onEvent defines the transition for an event.
An external transition must have a target state.
An internal transition must not have a target state.
A transition can have a guard expression.
The order in which the DSL reads the guard expressions is the order of evaluation.
The first guard that returns true selects the transition.
For one state and one event, only one transition can have no guard expression.
Examples:
onEvent(Event.EV1, guard = { flag == 1 }) { arg -> // internal transition with guard expression
}
onEvent(Event.EV1 to State.S2, guard = { flag == 2}) { arg -> // external transition with guard expression
}
onEvent(Event.EV1) { arg -> // internal transition
}
onEvent(Event.EV2 to State.S2) { arg -> // external transition
}
onEventPush
-
Arguments:
(event: E, targetMap: String, targetState: S [, guard:{}]) -
Mandatory: Optional
-
Cardinality: Multiple
There are two variations of the push transition. One variation has a guard expression. The other variation has no guard expression.
Example:
whenState(State.S1) {
onEventPush(Event.EV2, "mapName", State.S2) { // push transition to S2 in new map "mapName"
}
onEventPush(Event.EV2, "mapName", State.S2, guard = { flag == 1}) { // push transition to S2 in new map "mapName" with guard expression
}
}
onEventPop
-
Arguments:
(event: E [to targetState: S]|[,targetMap: String, targetState: S], [guard:{}]) -
Mandatory: Optional
-
Cardinality: Multiple
There are six variations of the pop transition. Each variation has or does not have a guard expression. Each variation has no target, a target state, or a target map and a target state. If the transition has a target map, a push transition follows the pop transition.
Example:
whenState(State.S1) {
onEventPop(Event.EV3) { // pop transition without targetState
}
onEventPop(Event.EV3, guard={ flag == 1 }) { // pop transition without targetState and guard expression
}
onEventPop(Event.EV3 to State.S2) { // pop transition on EV3 changing state to S2
}
onEventPop(Event.EV3 to State.S2, guard={ flag == 1 }) { // pop transition on EV3 changing state to S2 with a guard expression
}
onEventPop(Event.EV3, "newMap", State.S3) { // pop transition leading into new push transition to S3 in "newMap"
}
onEventPop(Event.EV3, "newMap", State.S3, guard={ flag == 1 }) { // pop transition leading into new push transition to S3 in "newMap" with a guard expression
}
}
timeout
-
Arguments:
(targetState: S, timeout: Long | C.() → Long, [guard:{}]) -
Mandatory: Optional
-
Cardinality: Multiple
Only asynchronous state machines have timeout transitions.
The state machine starts a timer when it enters the state. When the timer expires, the transition occurs. The state machine cancels the timer when it processes another transition.
The timeout is in milliseconds.
Give it as a Long, or as a lambda that has the context as this and returns a Long.
There are four variations.
Two variations add a guard expression.
The transition occurs only when the guard returns true.
timeoutPop
-
Arguments:
([targetMap: String], [targetState: S], timeout: Long | C.() → Long, [guard:{}]) -
Mandatory: Optional
-
Cardinality: Multiple
timeoutPop is a timeout transition that is also a pop transition.
The variations combine these options:
-
The timeout as a
Longor as a lambda. -
An optional guard expression.
-
No target, a target state, or a target map and a target state.
If the transition has a target map, a push transition follows the pop transition.
timeoutPush
-
Arguments:
(targetMap: String, targetState: S, timeout: Long | C.() → Long, [guard:{}]) -
Mandatory: Optional
-
Cardinality: Multiple
timeoutPush is a timeout transition that is also a push transition.
The variations combine these options:
-
The timeout as a
Longor as a lambda. -
An optional guard expression.
Operation
After you define a state machine, you can create an instance. You give the instance a context. You can also give it an externalized state.
When you call sendEvent, the state machine applies the event to the current state map.
The current state map is the top-level state map, unless you defined named state maps and a push transition occurred.
Send Event
For an external transition, the state machine runs these actions in this order:
-
sendEvent-
exitAction() -
action() -
entryAction()
-
For an internal transition, the state machine runs only action().
The state machine runs the exit action of the state first.
Then it runs the default exit action.
The exit action of the state is whenState/onExit.
If the current state map has no such action, the state machine uses whenState/onExit of the default state map.
The default exit action is stateMap/default/onExit.
If the current state map has none, the state machine uses the default exit action of the default state map.
The action is the first of these that exists:
-
stateMap/whenState/onEvent -
stateMap/whenState/default/action -
stateMap/default/action
The state machine runs the entry action of the state first.
Then it runs the default entry action.
The entry action of the state is whenState/onEntry.
If the current state map has no such action, the state machine uses whenState/onEntry of the default state map.
The default entry action is stateMap/default/onEntry.
If the current state map has none, the state machine uses the default entry action of the default state map.
The current state and the event select a set of transition rules.
The definition gives these rules.
If the rules have guarded transitions, the state machine evaluates the guard expressions in order.
The first guard that returns true selects the transition.
If no guard returns true, the state machine uses the transition that has no guard.
If no transition matches, the state machine runs the default action.
If there is no default action, sendEvent throws an exception.
The state machine runs onEntry and onExit only for external transitions.
An external transition has a target state.
An internal transition has no target state.
The current state selects the exit action. The target state selects the entry action.
After a transition completes, the state machine selects the automatic transitions of the current state.
Notes on Concurrency and Coroutines
AsyncTimer uses the CoroutineScope that you give when you create the instance.
It starts a coroutine in this scope.
The coroutine waits for the delay and then runs the trigger.
Tutorial
Simple turnstile example
Assume that you must manage the state of a simple lock.
The lock() function must run only when the lock is not locked.
The unlock() function must run only when the lock is locked.
Use the DSL to declare a state machine definition that matches the diagram:
State Diagram
State Table
| Start State | Event | End State | Action |
|---|---|---|---|
LOCKED |
PASS |
LOCKED |
alarm |
LOCKED |
COIN |
UNLOCKED |
unlock |
UNLOCKED |
PASS |
LOCKED |
lock |
UNLOCKED |
COIN |
UNLOCKED |
returnCoin |
Context class
class Turnstile(locked: Boolean = true) {
var locked: Boolean = locked
private set
fun unlock() {
require(locked) { "Cannot unlock when not locked" }
println("Unlock")
locked = false
}
fun lock() {
require(!locked) { "Cannot lock when locked" }
println("Lock")
locked = true
}
fun alarm() {
println("Alarm")
}
fun returnCoin() {
println("Return Coin")
}
override fun toString(): String {
return "Turnstile(locked=$locked)"
}
}
Enums for States and Events
Declare two enums. One enum has the states. The other enum has the events.
enum class TurnstileStates {
LOCKED,
UNLOCKED
}
/**
* @suppress
*/
enum class TurnstileEvents {
COIN,
PASS
}
Packaged definition and execution
class TurnstileFSM(turnstile: Turnstile, savedState: TurnstileStates? = null) {
private val fsm = definition.create(turnstile, savedState)
fun externalState() = fsm.currentState
fun coin() = fsm.sendEvent(TurnstileEvents.COIN)
fun pass() = fsm.sendEvent(TurnstileEvents.PASS)
fun allowedEvents() = fsm.allowed().map { it.name.lowercase() }.toSet()
companion object {
private val definition = stateMachine(
TurnstileStates.entries.toSet(),
TurnstileEvents.entries.toSet(),
Turnstile::class
) {
defaultInitialState = TurnstileStates.LOCKED
initialState {
if (locked)
TurnstileStates.LOCKED
else
TurnstileStates.UNLOCKED
}
onStateChange { oldState, newState ->
println("onStateChange:$oldState -> $newState")
}
default {
onEntry { startState, targetState, _ ->
println("entering:$startState -> $targetState for $this")
}
action { state, event, _ ->
println("Default action for state($state) -> on($event) for $this")
alarm()
}
onExit { startState, targetState, _ ->
println("exiting:$startState -> $targetState for $this")
}
}
whenState(TurnstileStates.LOCKED) {
onEvent(TurnstileEvents.COIN to TurnstileStates.UNLOCKED) {
unlock()
}
}
whenState(TurnstileStates.UNLOCKED) {
onEvent(TurnstileEvents.COIN) {
returnCoin()
}
onEvent(TurnstileEvents.PASS to TurnstileStates.LOCKED) {
lock()
}
}
}.build()
fun possibleEvents(state: TurnstileStates, includeDefault: Boolean = false) =
definition.possibleEvents(state, includeDefault)
}
}
Usage
Create an instance of the state machine. Give it the context that the actions operate on:
val turnstile = Turnstile()
val fsm = TurnstileFSM(turnstile)
The context is independent of the state machine.
When you send an event, the state machine can run actions:
// The state is LOCKED
fsm.coin()
// Expect the unlock() action. The new state is UNLOCKED
fsm.pass()
// Expect the lock() action. The new state is LOCKED
fsm.pass()
// Expect the alarm() action. The state stays LOCKED
fsm.coin()
// Expect the unlock() action. The new state is UNLOCKED
fsm.coin()
// Expect the returnCoin() action. The state stays UNLOCKED
Advanced Features
An event can have an argument. A state machine can also have named state maps, push transitions, pop transitions and automatic transitions.
Send the argument with the event:
fsm.sendEvent(EVENT1, arg)
The action receives the argument:
onEvent(EVENT1) { arg ->
val value = arg as Int
}
In this example, the COIN event has the value of the coin as its argument.
A named state map, coins, makes the decisions about coins.
A push transition goes to the coins state map and the COINS state.
Then the state machine runs an automatic transition when its guard returns true.
State Table
| Start State | Event | Guard Expression | End State | Action |
|---|---|---|---|---|
LOCKED |
PASS |
LOCKED |
alarm |
|
LOCKED |
COIN |
COINS |
coin(value) |
|
UNLOCKED |
PASS |
LOCKED |
lock |
|
COINS |
COIN |
COINS |
coin(value) |
|
COINS |
coins == requiredCoins |
UNLOCKED |
unlock |
|
COINS |
coins > requiredCoins |
UNLOCKED |
returnCoin(coins-requiredCoins), unlock |
A row without an event is an automatic transition. The COINS state is in a named state map. This shows how you can use state maps to group behaviour or to keep it separate.
Context class
The context class does not make decisions. It stores values and changes them in specific ways.
class PayingTurnstile(
val requiredCoins: Int,
locked: Boolean = true,
coins: Int = 0
) {
var coins: Int = coins
private set
var locked: Boolean = locked
private set
fun unlock() {
require(locked) { "Cannot unlock when not locked" }
require(coins >= requiredCoins) { "Not enough coins. ${requiredCoins - coins} required" }
println("Unlock")
locked = false
}
fun lock() {
require(!locked) { "Cannot lock when locked" }
require(coins == 0) { "Coins $coins must be returned" }
println("Lock")
locked = true
}
fun alarm() {
println("Alarm")
}
fun coin(value: Int): Int {
coins += value
println("Coin received=$value, Total=$coins")
return coins
}
fun returnCoin(returnCoins: Int) {
println("Return Coin:$returnCoins")
coins -= returnCoins
}
fun reset() {
coins = 0
println("Reset coins=$coins")
}
override fun toString(): String {
return "Turnstile(locked=$locked,coins=$coins)"
}
}
States and Events
enum class PayingTurnstileStates {
LOCKED,
COINS,
UNLOCKED
}
/**
* @suppress
*/
enum class PayingTurnstileEvents {
COIN,
PASS
}
The definition adds a state map that is named coins. The state map has the state COINS.
The state machine enters the state map when the turnstile has coins.
The guard expressions select the automatic transitions.
State machine definition packaged
This example shows how to externalize the state and how to create an instance from an externalized state.
The externalState function returns a list of states. The list has one state for each state map on the stack.
data class PayingTurnstileFSMExternalState(
val coins: Int,
val locked: Boolean,
val initialState: ExternalState<PayingTurnstileStates>
)
class PayingTurnstileFSM(
requiredCoins: Int,
savedState: PayingTurnstileFSMExternalState? = null
) {
// not private for visibility for tests
val turnstile: PayingTurnstile = PayingTurnstile(requiredCoins, savedState?.locked ?: true, savedState?.coins ?: 0)
val fsm = if (savedState != null) {
definition.create(turnstile, savedState.initialState)
} else {
definition.create(turnstile)
}
fun coin(value: Int) {
println("sendEvent:COIN:$value")
fsm.sendEvent(PayingTurnstileEvents.COIN, value)
}
fun pass() {
println("sendEvent:PASS")
fsm.sendEvent(PayingTurnstileEvents.PASS)
}
fun allowedEvents() = fsm.allowed().map { it.name.lowercase() }.toSet()
fun externalState(): PayingTurnstileFSMExternalState {
return PayingTurnstileFSMExternalState(turnstile.coins, turnstile.locked, fsm.externalState())
}
companion object {
val definition = stateMachine(
setOf(PayingTurnstileStates.LOCKED, PayingTurnstileStates.UNLOCKED),
PayingTurnstileEvents.entries.toSet(),
PayingTurnstile::class,
Int::class
) {
defaultInitialState = PayingTurnstileStates.LOCKED
invariant("negative coins") { coins >= 0 }
onStateChange { oldState, newState ->
println("onStateChange:$oldState -> $newState")
}
invariant("negative coins") { coins >= 0 }
default {
onEntry { _, targetState, arg ->
if (arg != null) {
println("entering:$targetState ($arg) for $this")
} else {
println("entering:$targetState for $this")
}
}
action { state, event, arg ->
if (arg != null) {
println("Default action for state($state) -> on($event, $arg) for $this")
} else {
println("Default action for state($state) -> on($event) for $this")
}
alarm()
}
onExit { startState, _, arg ->
if (arg != null) {
println("exiting:$startState ($arg) for $this")
} else {
println("exiting:$startState for $this")
}
}
}
stateMap("coins", setOf(PayingTurnstileStates.COINS)) {
whenState(PayingTurnstileStates.COINS) {
automaticPop(PayingTurnstileStates.UNLOCKED, guard = { coins > requiredCoins }) {
println("automaticPop:returnCoin")
returnCoin(coins - requiredCoins)
unlock()
reset()
}
automaticPop(PayingTurnstileStates.UNLOCKED, guard = { coins == requiredCoins }) {
println("automaticPop")
unlock()
reset()
}
onEvent(PayingTurnstileEvents.COIN) { value ->
requireNotNull(value) { "argument required for COIN" }
coin(value)
println("Coins=$coins")
if (coins < requiredCoins) {
println("Please add ${requiredCoins - coins}")
}
}
}
}
whenState(PayingTurnstileStates.LOCKED) {
// The coin brings amount to exact amount
onEventPush(PayingTurnstileEvents.COIN, "coins", PayingTurnstileStates.COINS) { value ->
requireNotNull(value) { "argument required for COIN" }
coin(value)
unlock()
reset()
}
// The coins add up to more than required
onEventPush(
PayingTurnstileEvents.COIN,
"coins",
PayingTurnstileStates.COINS,
guard = { value ->
requireNotNull(value) { "argument required for COIN" }
value + coins < requiredCoins
}
) { value ->
requireNotNull(value) { "argument required for COIN" }
println("PUSH TRANSITION")
coin(value)
println("Coins=$coins, Please add ${requiredCoins - coins}")
}
}
whenState(PayingTurnstileStates.UNLOCKED) {
onEvent(PayingTurnstileEvents.COIN) { value ->
requireNotNull(value) { "argument required for COIN" }
returnCoin(coin(value))
}
onEvent(PayingTurnstileEvents.PASS to PayingTurnstileStates.LOCKED) {
lock()
}
}
}.build()
}
}
Test
val fsm = PayingTurnstileFSM(50)
assertTrue(fsm.turnstile.locked)
println("External:${fsm.externalState()}")
println("--coin1")
fsm.coin(10)
assertTrue(fsm.turnstile.locked)
assertTrue(fsm.turnstile.coins == 10)
println("--coin2")
println("External:${fsm.externalState()}")
val externalState = fsm.externalState()
PayingTurnstileFSM(50, externalState).apply {
coin(60)
assertTrue(turnstile.coins == 0)
assertTrue(!turnstile.locked)
println("External:${externalState()}")
println("--pass1")
pass()
assertTrue(turnstile.locked)
println("--pass2")
pass()
println("--pass3")
pass()
println("--coin3")
coin(40)
assertTrue(turnstile.coins == 40)
println("--coin4")
coin(10)
assertTrue(turnstile.coins == 0)
assertTrue(!turnstile.locked)
}
Output
--coin1
sendEvent:COIN:10
entering:LOCKED ([10]) for Turnstile(locked=true,coins=0)
PUSH TRANSITION
Coin received=10, Total=10
Coins=10, Please add 40
--coin2
sendEvent:COIN:60
Coin received=60, Total=70
Return Coin:20
Unlock
Reset coins=0
entering:UNLOCKED ([60]) for Turnstile(locked=false,coins=0)
--pass1
sendEvent:PASS
exiting:UNLOCKED for Turnstile(locked=false,coins=0)
Lock
entering:LOCKED for Turnstile(locked=true,coins=0)
--pass2
sendEvent:PASS
Default action for state(LOCKED) -> on(PASS) for Turnstile(locked=true,coins=0)
Alarm
--pass3
sendEvent:PASS
Default action for state(LOCKED) -> on(PASS) for Turnstile(locked=true,coins=0)
Alarm
--coin3
sendEvent:COIN:40
entering:LOCKED ([40]) for Turnstile(locked=true,coins=0)
PUSH TRANSITION
Coin received=40, Total=40
Coins=40, Please add 10
--coin4
sendEvent:COIN:10
Coin received=10, Total=50
Unlock
Reset coins=0
entering:UNLOCKED ([10]) for Turnstile(locked=false,coins=0)
Secure Turnstile Example
This turnstile reads RFID cards or NFC cards. It does not accept coins.
The turnstile also has an override card. When the override is active, the turnstile lets any card pass, also an invalid card.
Guard expressions identify the override card and check if a card is valid. When a user taps the override card a second time, the turnstile cancels the override or locks, depending on the state.
State Table
| Start State | Event | Guard Expression | End State | Action |
|---|---|---|---|---|
LOCKED |
CARD(id) |
isOverrideCard(id) and overrideActive |
cancelOverride() |
|
LOCKED |
CARD(id) |
isOverrideCard(id) |
activateOverride() |
|
LOCKED |
CARD(id) |
overrideActive or isValidCard(id) |
UNLOCKED |
unlock() |
LOCKED |
CARD(id) |
not isValidCard(id) |
invalidCard() |
|
UNLOCKED |
PASS |
LOCKED |
lock() |
|
default |
buzzer() |
Context class
The context class does not make decisions about the behaviour of the turnstile. It gives information about the state of the turnstile and about the validity of cards. It stores values and changes them in specific ways.
class SecureTurnstile {
var locked: Boolean = true
private set
var overrideActive: Boolean = false
private set
fun activateOverride() {
overrideActive = true
println("override activated")
}
fun cancelOverride() {
overrideActive = false
println("override canceled")
}
fun lock() {
println("lock")
locked = true
overrideActive = false
}
fun unlock() {
println("unlock")
locked = false
overrideActive = false
}
fun buzzer() {
println("BUZZER")
}
fun invalidCard(cardId: Int) {
println("Invalid card $cardId")
}
fun isOverrideCard(cardId: Int): Boolean {
return cardId == 42
}
fun isValidCard(cardId: Int): Boolean {
return cardId % 2 == 1
}
}
States and Events
enum class SecureTurnstileEvents {
CARD,
PASS
}
State machine definition packaged
class SecureTurnstileFSM(secureTurnstile: SecureTurnstile) {
companion object {
val definition = stateMachine(
SecureTurnstileStates.entries.toSet(),
SecureTurnstileEvents.entries.toSet(),
SecureTurnstile::class,
Int::class
) {
defaultInitialState = SecureTurnstileStates.LOCKED
initialState { if (locked) SecureTurnstileStates.LOCKED else SecureTurnstileStates.UNLOCKED }
default {
action { _, _, _ ->
buzzer()
}
}
onStateChange { oldState, newState ->
println("onStateChange:$oldState -> $newState")
}
whenState(SecureTurnstileStates.OVERRIDE) {
onEvent(
SecureTurnstileEvents.CARD to SecureTurnstileStates.LOCKED,
guard = { cardId ->
requireNotNull(cardId)
isOverrideCard(cardId)
}
) {
cancelOverride()
}
onEvent(
SecureTurnstileEvents.CARD to SecureTurnstileStates.UNLOCKED,
guard = { cardId ->
requireNotNull(cardId)
!isValidCard(cardId)
}
) { cardId ->
println("Allowed invalid card:$cardId")
unlock()
}
onEvent(
SecureTurnstileEvents.CARD to SecureTurnstileStates.UNLOCKED,
guard = { cardId ->
requireNotNull(cardId)
isValidCard(cardId)
}
) { cardId ->
println("Allowing valid card:${cardId}")
unlock()
}
}
whenState(SecureTurnstileStates.LOCKED) {
onEvent(
SecureTurnstileEvents.CARD to SecureTurnstileStates.OVERRIDE,
guard = { cardId ->
requireNotNull(cardId)
isOverrideCard(cardId)
}
) {
activateOverride()
}
onEvent(
SecureTurnstileEvents.CARD to SecureTurnstileStates.UNLOCKED,
guard = { cardId ->
requireNotNull(cardId)
isValidCard(cardId)
}
) {
unlock()
}
onEvent(
SecureTurnstileEvents.CARD,
guard = { cardId ->
requireNotNull(cardId) { "cardId is required" }
!isValidCard(cardId)
}
) { cardId ->
requireNotNull(cardId)
invalidCard(cardId)
}
}
whenState(SecureTurnstileStates.UNLOCKED) {
onEvent(
SecureTurnstileEvents.CARD to SecureTurnstileStates.LOCKED,
guard = { cardId ->
requireNotNull(cardId)
isOverrideCard(cardId)
}
) {
lock()
}
onEvent(SecureTurnstileEvents.PASS to SecureTurnstileStates.LOCKED) {
lock()
}
}
}.build()
}
private val fsm = definition.create(secureTurnstile)
fun card(cardId: Int) = fsm.sendEvent(SecureTurnstileEvents.CARD, cardId)
fun pass() = fsm.sendEvent(SecureTurnstileEvents.PASS)
fun allowEvent(): Set<String> = fsm.allowed().map { it.name.lowercase() }.toSet()
}
Test
val fsm = PayingTurnstileFSM(50)
assertTrue(fsm.turnstile.locked)
println("External:${fsm.externalState()}")
println("--coin1")
fsm.coin(10)
assertTrue(fsm.turnstile.locked)
assertTrue(fsm.turnstile.coins == 10)
println("--coin2")
println("External:${fsm.externalState()}")
val externalState = fsm.externalState()
PayingTurnstileFSM(50, externalState).apply {
coin(60)
assertTrue(turnstile.coins == 0)
assertTrue(!turnstile.locked)
println("External:${externalState()}")
println("--pass1")
pass()
assertTrue(turnstile.locked)
println("--pass2")
pass()
println("--pass3")
pass()
println("--coin3")
coin(40)
assertTrue(turnstile.coins == 40)
println("--coin4")
coin(10)
assertTrue(turnstile.coins == 0)
assertTrue(!turnstile.locked)
}
Packet Reader Example
The diagram above combines some transitions to keep the diagram short. In the implementation, all control characters are one type of event, and guard expressions tell them apart. Each event has the received byte as its argument. The event type is BYTE, CTRL or ESC:
-
ESC is 0x1B.
-
CTRL is SOH, STX, ETX, EOT, ACK or NAK.
-
BYTE is any other character.
Context Classes
The checksum in this example is simple. The checksum has one character for each field. This character is the same as the first character of the field.
class Block {
private val byteArray = mutableListOf<Byte>()
fun addByte(byte: Int) {
byteArray.add(byte.toByte())
}
fun toByteArray(): ByteArray = byteArray.toByteArray()
fun size() = byteArray.size
}
interface ProtocolHandler {
fun sendNACK()
fun sendACK()
}
interface PacketHandler : ProtocolHandler {
val checksumValid: Boolean
fun print()
fun addField()
fun endField()
fun addByte(byte: Int)
fun addChecksum(byte: Int)
fun checksum()
}
class ProtocolSender : ProtocolHandler {
override fun sendNACK() {
println("NACK")
}
override fun sendACK() {
println("ACK")
}
}
class Packet(private val protocolHandler: ProtocolHandler) :
PacketHandler,
ProtocolHandler by protocolHandler {
val fields = mutableListOf<ByteArray>()
private var currentField: Block? = null
private var _checksumValid: Boolean = false
override val checksumValid: Boolean
get() = _checksumValid
private val checkSum = Block()
override fun print() {
println("Checksum:$checksumValid:Fields:${fields.size}")
fields.forEachIndexed { index, bytes ->
print("FLD:$index:")
bytes.forEach { byte ->
val hex = byte.toString(16).padStart(2, '0')
print(" $hex")
}
println()
}
println()
}
override fun addField() {
currentField = Block()
}
override fun endField() {
val field = currentField
requireNotNull(field) { "expected currentField to have a value" }
fields.add(field.toByteArray())
currentField = null
}
override fun addByte(byte: Int) {
val field = currentField
preconditionNotNull(field) { "expected currentField to have a value" }
field.addByte(byte)
}
override fun addChecksum(byte: Int) {
checkSum.addByte(byte)
}
override fun checksum() {
require(checkSum.size() > 0)
val checksumBytes = checkSum.toByteArray()
_checksumValid = if (checksumBytes.size == fields.size) {
checksumBytes.mapIndexed { index, cs ->
cs == fields[index][0]
}.reduce { a, b -> a && b }
} else {
false
}
}
}
States and Events
class CharacterConstants {
companion object {
const val SOH = 0x01
const val STX = 0x02
const val ETX = 0x03
const val EOT = 0x04
const val ACK = 0x06
const val NAK = 0x15
const val ESC = 0x1b
}
}
/**
* CTRL :
* BYTE everything else
*/
enum class ReaderEvents {
BYTE, // everything else
CTRL, // SOH, EOT, STX, ETX, ACK, NAK
ESC // ESC = 0x1B
}
enum class ReaderStates {
START,
RCVPCKT,
RCVDATA,
RCVESC,
RCVCHK,
RCVCHKESC,
CHKSUM,
END
}
Packaged FSM
class PacketReaderFSM(packetHandler: PacketHandler) {
companion object {
val definition = stateMachine(
ReaderStates.entries.toSet(),
ReaderEvents.entries.toSet(),
PacketHandler::class,
Int::class
) {
defaultInitialState = ReaderStates.START
onStateChange { oldState, newState ->
println("onStateChange:$oldState -> $newState")
}
default {
onEvent(ReaderEvents.BYTE to ReaderStates.END) {
sendNACK()
}
onEvent(ReaderEvents.CTRL to ReaderStates.END) {
sendNACK()
}
onEvent(ReaderEvents.ESC to ReaderStates.END) {
sendNACK()
}
}
whenState(ReaderStates.START) {
onEvent(
ReaderEvents.CTRL to ReaderStates.RCVPCKT,
guard = { byte -> byte == CharacterConstants.SOH }
) {}
}
whenState(ReaderStates.RCVPCKT) {
onEvent(ReaderEvents.CTRL to ReaderStates.RCVDATA, guard = { byte -> byte == CharacterConstants.STX }) {
addField()
}
onEvent(ReaderEvents.BYTE to ReaderStates.RCVCHK) { byte ->
requireNotNull(byte)
addChecksum(byte)
}
}
whenState(ReaderStates.RCVDATA) {
onEvent(ReaderEvents.BYTE) { byte ->
requireNotNull(byte)
addByte(byte)
}
onEvent(ReaderEvents.CTRL to ReaderStates.RCVPCKT, guard = { byte -> byte == CharacterConstants.ETX }) {
endField()
}
onEvent(ReaderEvents.ESC to ReaderStates.RCVESC) {}
}
whenState(ReaderStates.RCVESC) {
onEvent(ReaderEvents.ESC to ReaderStates.RCVDATA) {
addByte(CharacterConstants.ESC)
}
onEvent(ReaderEvents.CTRL to ReaderStates.RCVDATA) { byte ->
requireNotNull(byte)
addByte(byte)
}
}
whenState(ReaderStates.RCVCHK) {
onEvent(ReaderEvents.BYTE) { byte ->
requireNotNull(byte)
addChecksum(byte)
}
onEvent(ReaderEvents.ESC to ReaderStates.RCVCHKESC) {}
onEvent(ReaderEvents.CTRL to ReaderStates.CHKSUM, guard = { byte -> byte == CharacterConstants.EOT }) {
checksum()
}
}
whenState(ReaderStates.CHKSUM) {
automatic(ReaderStates.END, guard = { !checksumValid }) {
sendNACK()
}
automatic(ReaderStates.END, guard = { checksumValid }) {
sendACK()
}
}
whenState(ReaderStates.RCVCHKESC) {
onEvent(ReaderEvents.ESC to ReaderStates.RCVCHK) {
addChecksum(CharacterConstants.ESC)
}
onEvent(ReaderEvents.CTRL to ReaderStates.RCVCHK) { byte ->
requireNotNull(byte)
addChecksum(byte)
}
}
}.build()
}
private val fsm = definition.create(packetHandler)
fun receiveByte(byte: Int) {
when (byte) {
CharacterConstants.ESC -> fsm.sendEvent(ReaderEvents.ESC, CharacterConstants.ESC)
CharacterConstants.SOH,
CharacterConstants.EOT,
CharacterConstants.ETX,
CharacterConstants.STX,
CharacterConstants.ACK,
CharacterConstants.NAK -> fsm.sendEvent(ReaderEvents.CTRL, byte)
else -> fsm.sendEvent(ReaderEvents.BYTE, byte)
}
}
}
Tests
class PacketReaderTests {
@Test
fun testReaderExpectACK() {
val protocolHandler = ProtocolSender()
val packetReader = Packet(protocolHandler)
val fsm = PacketReaderFSM(packetReader)
val stream =
listOf(
CharacterConstants.SOH,
CharacterConstants.STX,
'A'.code,
'B'.code,
'C'.code,
CharacterConstants.ETX,
'A'.code,
CharacterConstants.EOT
)
stream.forEach { byte ->
fsm.receiveByte(byte)
}
packetReader.print()
protocolHandler.sendACK()
assertTrue { packetReader.checksumValid }
}
@Test
fun testReaderESCExpectACK() {
val protocolHandler = ProtocolSender()
val packetReader = Packet(protocolHandler)
val fsm = PacketReaderFSM(packetReader)
val stream =
listOf(
CharacterConstants.SOH,
CharacterConstants.STX,
'A'.code,
CharacterConstants.ESC,
CharacterConstants.EOT,
'C'.code,
CharacterConstants.ETX,
'A'.code,
CharacterConstants.EOT
)
stream.forEach { byte ->
fsm.receiveByte(byte)
}
packetReader.print()
assertTrue { packetReader.checksumValid }
assertTrue { packetReader.fields.size == 1 }
assertTrue { packetReader.fields[0].size == 3 }
assertTrue { packetReader.fields[0][1].toInt() == CharacterConstants.EOT }
}
@Test
fun testReaderESCExpectNACK() {
val protocolHandler = ProtocolSender()
val packetReader = Packet(protocolHandler)
val fsm = PacketReaderFSM(packetReader)
val stream =
listOf(
CharacterConstants.SOH,
CharacterConstants.STX,
'A'.code,
CharacterConstants.ESC,
'C'.code,
CharacterConstants.ETX,
'A'.code,
CharacterConstants.EOT
)
stream.forEach { byte ->
fsm.receiveByte(byte)
}
packetReader.print()
assertFalse { packetReader.checksumValid }
assertTrue { packetReader.fields.isEmpty() }
}
@Test
fun testReaderExpectNACK() {
val protocolHandler = ProtocolSender()
val packetReader = Packet(protocolHandler)
val fsm = PacketReaderFSM(packetReader)
val stream =
listOf(
CharacterConstants.SOH,
CharacterConstants.STX,
'A'.code,
'B'.code,
'C'.code,
CharacterConstants.ETX,
'B'.code,
CharacterConstants.EOT
)
stream.forEach { byte ->
fsm.receiveByte(byte)
}
packetReader.print()
assertFalse { packetReader.checksumValid }
}
@Test
fun testReaderMultipleFieldsExpectACK() {
val protocolHandler = ProtocolSender()
val packetReader = Packet(protocolHandler)
val fsm = PacketReaderFSM(packetReader)
val stream =
listOf(
CharacterConstants.SOH,
CharacterConstants.STX,
'A'.code,
'B'.code,
'C'.code,
CharacterConstants.ETX,
CharacterConstants.STX,
'D'.code,
'E'.code,
'F'.code,
CharacterConstants.ETX,
'A'.code,
'D'.code,
CharacterConstants.EOT
)
stream.forEach { byte ->
fsm.receiveByte(byte)
}
packetReader.print()
assertTrue { packetReader.checksumValid }
assertTrue { packetReader.fields.size == 2 }
}
}
Immutable Context Example
Use this example when you want an immutable context. Actions do not change the context. They return a new context.
Immutable Context
The immutable context does not change a variable. It returns a copy that has the new values.
data class ImmutableLock(val locked: Int = 1) {
fun lock(): ImmutableLock {
require(locked == 0)
println("Lock")
return copy(locked = locked + 1)
}
fun doubleLock(): ImmutableLock {
require(locked == 1)
println("DoubleLock")
return copy(locked = locked + 1)
}
fun unlock(): ImmutableLock {
require(locked == 1)
println("Unlock")
return copy(locked = locked - 1)
}
fun doubleUnlock(): ImmutableLock {
require(locked == 2)
println("DoubleUnlock")
return copy(locked = locked - 1)
}
override fun toString(): String {
return "Lock(locked=$locked)"
}
}
Definition
The definition has one function. The function applies an event to a context and returns the new context.
class ImmutableLockFSM {
companion object {
fun handleEvent(context: ImmutableLock, event: LockEvents): ImmutableLock {
val fsm = definition.create(context)
return fsm.sendEvent(event, context) ?: error("Expected context not null")
}
private val definition = functionalStateMachine(
LockStates.entries.toSet(),
LockEvents.entries.toSet(),
ImmutableLock::class
) {
defaultInitialState = LockStates.LOCKED
initialState {
when (locked) {
0 -> LockStates.UNLOCKED
1 -> LockStates.LOCKED
2 -> LockStates.DOUBLE_LOCKED
else -> error("Invalid state locked=$locked")
}
}
invariant("invalid locked value") { locked in 0..2 }
onStateChange { oldState, newState ->
println("onStateChange:$oldState -> $newState")
}
default {
action { state, event, _ ->
println("Default action for state($state) -> on($event) for $this")
this
}
onEntry { startState, targetState, _ ->
println("entering:$startState -> $targetState for $this")
}
onExit { startState, targetState, _ ->
println("exiting:$startState -> $targetState for $this")
}
}
whenState(LockStates.LOCKED) {
onEvent(LockEvents.LOCK to LockStates.DOUBLE_LOCKED) {
doubleLock()
}
onEvent(LockEvents.UNLOCK to LockStates.UNLOCKED) {
unlock()
}
}
whenState(LockStates.DOUBLE_LOCKED) {
onEvent(LockEvents.UNLOCK to LockStates.LOCKED) {
doubleUnlock()
}
}
whenState(LockStates.UNLOCKED) {
onEvent(LockEvents.LOCK to LockStates.LOCKED) {
lock()
}
}
}.build()
}
}
operator fun ImmutableLock.plus(event: LockEvents): ImmutableLock {
return ImmutableLockFSM.handleEvent(this, event)
}
Usage
The example also has an overloaded plus operator.
Use it to apply an event to a context.
val lock = ImmutableLock(0)
val locked = lock + LockEvents.LOCK
assertEquals(locked.locked, 1)
val doubleLocked = locked + LockEvents.LOCK
assertEquals(doubleLocked.locked, 2)
When the argument of the action is not the context, use a Pair. Use a Pair also when you need the state separately:
val locked = ImmutablePayingTurnstile(50)
val (state, newTurnStile) = locked + (COIN to 10)
In this example, the argument type is Int. The return type is Pair<LockStates, ImmutablePayingTurnstile>.
The handleEvent function is:
fun handleEvent(context: ImmutablePayingTurnstile, event: Pair<LockEvents, Int>): Pair<LockStates,ImmutablePayingTurnstile> {
val fsm = definition.create(context)
val result = fsm.sendEvent(event.first, event.second) ?: error("Expected context not null")
return Pair(fsm.currentState, result)
}
Secure Turnstile with Timeout Example
This example adds a timeout transition to the Secure Turnstile. When the turnstile is UNLOCKED for 500 ms, it locks.
State Table
TimerSecureTurnstileFSM State Map
| Start | Event[Guard] | Target | Action |
|---|---|---|---|
LOCKED |
CARD |
LOCKED |
|
LOCKED |
CARD |
LOCKED |
|
LOCKED |
CARD |
UNLOCKED |
|
LOCKED |
CARD |
LOCKED |
|
UNLOCKED |
<<timeout = 500>> |
LOCKED |
|
UNLOCKED |
CARD |
LOCKED |
|
UNLOCKED |
PASS |
LOCKED |
|
Context class
The context class does not make decisions about the behaviour of the turnstile. It gives information about the state of the turnstile and about the validity of cards. It stores values and changes them in specific ways.
class TimerSecureTurnstile {
var locked: Boolean = true
private set
var overrideActive: Boolean = false
private set
val timeout = 500L
fun activateOverride() {
overrideActive = true
println("override activated")
}
fun cancelOverride() {
overrideActive = false
println("override canceled")
}
fun lock() {
println("lock")
locked = true
overrideActive = false
}
fun unlock() {
println("unlock")
locked = false
overrideActive = false
}
fun buzzer() {
println("BUZZER")
}
fun invalidCard(cardId: Int) {
println("Invalid card $cardId")
}
fun isOverrideCard(cardId: Int): Boolean {
return cardId == 42
}
fun isValidCard(cardId: Int): Boolean {
return cardId % 2 == 1
}
}
States and Events
enum class TimeoutSecureTurnstileEvents {
CARD,
PASS
}
State machine definition packaged
class TimerSecureTurnstileFSM(secureTurnstile: TimerSecureTurnstile, coroutineScope: CoroutineScope) {
companion object {
val definition = asyncStateMachine(
TimeoutSecureTurnstileStates.entries.toSet(),
TimeoutSecureTurnstileEvents.entries.toSet(),
TimerSecureTurnstile::class,
Int::class
) {
defaultInitialState = TimeoutSecureTurnstileStates.LOCKED
initialState { if (locked) TimeoutSecureTurnstileStates.LOCKED else TimeoutSecureTurnstileStates.UNLOCKED }
default {
action { _, _, _ ->
buzzer()
}
}
onStateChange { oldState, newState ->
println("onStateChange:$oldState -> $newState")
}
whenState(TimeoutSecureTurnstileStates.LOCKED) {
onEvent(
TimeoutSecureTurnstileEvents.CARD,
guard = { cardId ->
requireNotNull(cardId)
isOverrideCard(cardId) && overrideActive
}
) {
cancelOverride()
}
onEvent(
TimeoutSecureTurnstileEvents.CARD,
guard = { cardId ->
requireNotNull(cardId)
isOverrideCard(cardId)
}
) {
activateOverride()
}
onEvent(
TimeoutSecureTurnstileEvents.CARD to TimeoutSecureTurnstileStates.UNLOCKED,
guard = { cardId ->
requireNotNull(cardId)
overrideActive || isValidCard(cardId)
}
) {
unlock()
}
onEvent(
TimeoutSecureTurnstileEvents.CARD,
guard = { cardId ->
requireNotNull(cardId) { "cardId is required" }
!isValidCard(cardId)
}
) { cardId ->
requireNotNull(cardId)
invalidCard(cardId)
}
}
whenState(TimeoutSecureTurnstileStates.UNLOCKED) {
timeout(TimeoutSecureTurnstileStates.LOCKED, { timeout }) {
println("Timeout. Locking")
lock()
}
onEvent(
TimeoutSecureTurnstileEvents.CARD to TimeoutSecureTurnstileStates.LOCKED,
guard = { cardId ->
requireNotNull(cardId)
isOverrideCard(cardId)
}
) {
lock()
}
onEvent(TimeoutSecureTurnstileEvents.PASS to TimeoutSecureTurnstileStates.LOCKED) {
lock()
}
}
}.build()
}
private val fsm = definition.create(secureTurnstile, coroutineScope)
suspend fun card(cardId: Int) = fsm.sendEvent(TimeoutSecureTurnstileEvents.CARD, cardId)
suspend fun pass() = fsm.sendEvent(TimeoutSecureTurnstileEvents.PASS)
fun allowEvent(): Set<String> = fsm.allowed().map { it.name.lowercase() }.toSet()
}
Test
@Test
fun testTimeout() {
val turnstile = TimerSecureTurnstile()
val fsm = TimerSecureTurnstileFSM(turnstile, coroutineScope)
assertTrue { turnstile.locked }
println("Card 1")
runBlocking {
fsm.card(1)
println("Assertion")
assertTrue { !turnstile.locked }
println("Delay:100")
delay(100L)
assertTrue { !turnstile.locked }
println("Delay:1000")
delay(1000L)
println("Assertion")
assertTrue { turnstile.locked }
}
}
Further thoughts
The escape handling of the packet reader can be a separate state map. The current implementation has a problem: the escaped byte must go into a different buffer.
A state map could receive a different context from the main context.
This context would be an interface or a class that shows only a part of the full context.
In this example, the state map would receive Block.
The state map adds the byte and then runs a pop transition.
If the character is not valid, the state map still goes to the end state.