Search code examples
c++booststate-machineboost-statechart

Notification about state change in Boost Statechart


Is there a straightforward method of registering to state change in Boost Statechart?

For the Digital Camera example, let's say I decide to add a GUI to the application. Is there a possibility to be notified about transition between states, other than querying the states?

if(0 != state_cast<const State1 *>())
{
    context<OuterCotext>().Notify(1);
}
else if(0 != state_cast<const State2 *>())
{
    context<OuterCotext>().Notify(2);
}

Solution

  • The easiest way to know you've changed state is that you enter the destructor of the previous state and then the constructor of the new state.

    #include <boost/statechart/state_machine.hpp>
    #include <boost/statechart/simple_state.hpp>
    #include <iostream>
    
    namespace sc = boost::statechart;
    
    struct Greeting;
    struct Machine : sc::state_machine< Machine, S1> {};
    
    struct S1 : sc::simple_state<S1, Machine>
    {
        S1() 
        { // entry
            std::cout << "Enter S1\n"; 
        } 
        ~S1() 
        { // exit
            std::cout << "Exit S1\n"; 
        } 
    };
    
    int main()
    {
        Machine myMachine;
        myMachine.initiate();
    
        return 0;
    }
    

    Demo

    In boost.statechart the onEntry/onExit actions are implemented by constructor/destructor pairs since a state instance is only alive for as along as the state is the current state of the machine.

    So everything you want to record, register, log upon state change (entry or exit) you can do it inside those special functions.