The C++ state machine context

The context class is the fundamental class generated and directly used by your code. The following documentation explains how the context class is named, what are the constructor parameters, how to perform the second phase initialization with EnterInitialState(), and finally, how to find out that the context has ended.

Context name

By default the context class name is based on the filename without extension, then it is suffixed by "Context":

MyStateMachine.fsmcpp => MyStateMachineContext

It is also possible to set the context class name with the context element:

Context contructor

The constructor parameters are defined by the object tags in the settings element. When the state machine is asynchronous, a parameter holding the event loop is added to the constructor. The type of parameter depends on the underlying library: Qt, Boost or libev

Synchronous context constructor

WashingMachine.fsmcpp

Synchronous constructor declaration

Synchronous context instantiation

Asynchronous context constructor with Qt

Tr69ConnectionRequestResponder.fsmcpp

Qt asynchronous constructor declaration

Qt asynchronous context instantiation

Asynchronous context constructor with Boost

Door.fsmcpp

Boost asynchronous constructor declaration

Boost asynchronous context instantiation

Asynchronous context constructor with libev

Blink.fsmcpp

Libev asynchronous constructor declaration

Libev context instantiation

EnterInitialState

After the creation of an instance of the context, one may invoke the method EnterInitialState() to call the OnEntry() method from the root state to the initial state.

Consider the Led state machine example:

In this case, EnterInitialState() will call ledPrivate.DoOff() to make sure the led is switched off.

Context ending and final state

Final states are states which have the attribute kind set to final:

When the machine enters this final state, the context fires a callback to the application. How it is implemented depends if Qt, Boost or standard C++ is used.

Final state with Qt

In case Qt is used, the generated context has a signal end() that is emitted when a final state is reached.

Add a private slot in your application named for instance contextEnd()

Declaration:

Implementation:

Connect this slot to context signal end() in the constructor:

Final state with Boost or STL

Make your application class inherits from the interface fsm::IManagement which has one funtion OnEnd() to implement:

After the context creation, set the management interface with the SetManagement funtion and implement OnEnd()