Skip to content

Latest commit

 

History

History
 
 

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 

Readme.md

Chapter - 9 : The State Machine Contexts

Till now we have seen state machines and state created using struct. However, the statemachine as well as the state themselves can have the contexts of their own which needs to be accessed during different transitions.

Boost::Statechart context allows accessing of statemachine and state contexts from event handlers.

9.1 : Accessing the context

Let's have a two state statemachine (firstState & secondState) with its own variable called stateVariable which will be initialized with a value (say 100) within the statemachine constructor.

struct firstState;
struct secondState;

struct statemachine : sc::state_machine<statemachine, firstState> {
	int stateVariable;
	statemachine() : stateVariable(100) {
		cout << "StateMachine State Variable Constructor Value = " << stateVariable << endl;
	}
};

Let's also create custom events and event handlers to handle the transiting into second state as well as looking into the state variables

struct event_MoveToSecondState : sc::event<event_MoveToSecondState> {};
struct event_CheckSMVariable : sc::event<event_CheckSMVariable> {};

Finally, lets create the event handlers in states to access Statemachine context. In firstState the code will change the value of stateVariable and in secondState the code will verify that the value is indeed incremented.

struct firstState : sc::simple_state<firstState, statemachine> {
	typedef sc::custom_reaction<event_MoveToSecondState> reactions;
	sc::result react(const event_MoveToSecondState & event) {
		context<statemachine>().stateVariable = 200;
		return transit<secondState>();
	}
};
struct secondState : sc::simple_state<secondState, statemachine> {
	typedef sc::custom_reaction<event_CheckSMVariable> reactions;
	sc::result react(const event_CheckSMVariable & event) {
		cout << "Inside event => event_CheckSMVariable | StateMachine State Variable Value = " << context<statemachine>().stateVariable << endl;
		return discard_event();
	}
};

// The Main function

int main() {
	statemachine sm;
	sm.initiate();
	sm.process_event(event_MoveToSecondState());
	sm.process_event(event_CheckSMVariable());
  return 0;
}
  • NOTE : The context<>() and some other functions can't be used inside the constructor of the state derived from the simple_state<> template. If an entry action needs to access the "outside world", the state must derive from state<> instead and must implement appropriate forwarding constructor.