Class HierarchicalStateMachine

Public Member Functions

 
explicitHierarchicalStateMachine (const StateID_t initialState)
 Constructor that sets the initial state of the HSM.
 
virtual~HierarchicalStateMachine ()
 Destructor.
 
voidsetInitialState (const StateID_t initialState)
 Sets the initial state of the HSM.
 
virtual boolinitialize (const std::weak_ptr<IHsmEventDispatcher> &dispatcher)
 Initializes the HSM.
 
std::weak_ptr<IHsmEventDispatcher>dispatcher ()
 Returns dispatcher that was passed to initialize() method.
 
boolisInitialized ()
 Checks initialization status of HSM.
 
voidrelease ()
 Releases dispatcher instance and frees any allocated internal resources.
 
voidregisterFailedTransitionCallback (HsmTransitionFailedCallback_t onFailedTransition)
 Registers a callback function to be called when a transition fails.
 
voidregisterFailedTransitionCallback (HsmHandlerClass *handler, void (HsmHandlerClass::* onFailedTransition)(const std::list<StateID_t>&, const EventID_t, const VariantVector_t&))
 Registers a class member as a callback function to be called when a transition fails.
 
voidregisterState (const StateID_t state, HsmStateChangedCallback_t onStateChanged = nullptr, HsmStateEnterCallback_t onEntering = nullptr, HsmStateExitCallback_t onExiting = nullptr)
 Registers a new state and optional state callbacks.
 
voidregisterState (const StateID_t state, HsmHandlerClass *handler = nullptr, void (HsmHandlerClass::* onStateChanged)(const VariantVector_t&) = nullptr, bool (HsmHandlerClass::* onEntering)(const VariantVector_t&) = nullptr, bool (HsmHandlerClass::* onExiting)() = nullptr)
 Registers a new state and optional state callbacks (using class members).
 
voidregisterFinalState (const StateID_t state, const EventID_t event = INVALID_HSM_EVENT_ID, HsmStateChangedCallback_t onStateChanged = nullptr, HsmStateEnterCallback_t onEntering = nullptr, HsmStateExitCallback_t onExiting = nullptr)
 Registers state as final.
 
voidregisterFinalState (const StateID_t state, const EventID_t event = INVALID_HSM_EVENT_ID, HsmHandlerClass *handler = nullptr, void (HsmHandlerClass::* onStateChanged)(const VariantVector_t&) = nullptr, bool (HsmHandlerClass::* onEntering)(const VariantVector_t&) = nullptr, bool (HsmHandlerClass::* onExiting)() = nullptr)
 Registers a state as final using class members as callbacks.
 
voidregisterHistory (const StateID_t parent, const StateID_t historyState, const HistoryType type = HistoryType::SHALLOW, const StateID_t defaultTarget = INVALID_HSM_STATE_ID, HsmTransitionCallback_t transitionCallback = nullptr)
 Registers a history state with the state machine.
 
voidregisterHistory (const StateID_t parent, const StateID_t historyState, const HistoryType type = HistoryType::SHALLOW, const StateID_t defaultTarget = INVALID_HSM_STATE_ID, HsmHandlerClass *handler = nullptr, void (HsmHandlerClass::* transitionCallback)(const VariantVector_t&) = nullptr)
 Registers a history state with the state machine (using class member as a callback)
 
boolregisterSubstate (const StateID_t parent, const StateID_t substate)
 Registers state as a substate.
 
boolregisterSubstateEntryPoint (const StateID_t parent, const StateID_t substate, const EventID_t onEvent = INVALID_HSM_EVENT_ID, HsmTransitionConditionCallback_t conditionCallback = nullptr, const bool expectedConditionValue = true)
 Registers an entry point for a parent state.
 
boolregisterSubstateEntryPoint (const StateID_t parent, const StateID_t substate, const EventID_t onEvent = INVALID_HSM_EVENT_ID, HsmHandlerClass *handler = nullptr, bool (HsmHandlerClass::* conditionCallback)(const VariantVector_t&) = nullptr, const bool expectedConditionValue = true)
 Registers an entry point for a parent state with class member as a callback.
 
voidregisterTimer (const TimerID_t timerID, const EventID_t event)
 Registers a timer to be used inside HSM.
 
boolregisterStateAction (const StateID_t state, const StateActionTrigger actionTrigger, const StateAction action, Args&&... args)
 Registers a state action with optional arguments.
 
voidregisterTransition (const StateID_t fromState, const StateID_t toState, const EventID_t onEvent, HsmTransitionCallback_t transitionCallback = nullptr, HsmTransitionConditionCallback_t conditionCallback = nullptr, const bool expectedConditionValue = true)
 Registers a transition from one state to another.
 
voidregisterTransition (const StateID_t fromState, const StateID_t toState, const EventID_t onEvent, HsmHandlerClass *handler = nullptr, void (HsmHandlerClass::* transitionCallback)(const VariantVector_t&) = nullptr, bool (HsmHandlerClass::* conditionCallback)(const VariantVector_t&) = nullptr, const bool expectedConditionValue = true)
 Registers a transition from one state to another.
 
voidregisterSelfTransition (const StateID_t state, const EventID_t onEvent, const TransitionType type = TransitionType::EXTERNAL_TRANSITION, HsmTransitionCallback_t transitionCallback = nullptr, HsmTransitionConditionCallback_t conditionCallback = nullptr, const bool expectedConditionValue = true)
 Register a self-transition for a state.
 
voidregisterSelfTransition (const StateID_t state, const EventID_t onEvent, const TransitionType type = TransitionType::EXTERNAL_TRANSITION, HsmHandlerClass *handler = nullptr, void (HsmHandlerClass::* transitionCallback)(const VariantVector_t&) = nullptr, bool (HsmHandlerClass::* conditionCallback)(const VariantVector_t&) = nullptr, const bool expectedConditionValue = true)
 Register a self-transition for a state (using class members as callback).
 
StateID_tgetLastActiveState ()
 Get the ID of the last activated state.
 
const std::list<StateID_t> &getActiveStates ()
 Get the list of currently active states.
 
boolisStateActive (const StateID_t state)
 Check if a state is active.
 
voidtransition (const EventID_t event, Args&&... args)
 Trigger a transition in the HSM.
 
booltransitionEx (const EventID_t event, const bool clearQueue, const bool sync, const int timeoutMs, Args&&... args)
 Trigger a transition in the HSM.
 
voidtransitionWithArgsArray (const EventID_t event, VariantVector_t &&args)
 Trigger a transition in the HSM with arguments passed as a vector.
 
booltransitionExWithArgsArray (const EventID_t event, const bool clearQueue, const bool sync, const int timeoutMs, VariantVector_t &&args)
 Trigger a transition in the HSM with arguments passed as a vector.
 
booltransitionSync (const EventID_t event, const int timeoutMs, Args&&... args)
 Trigger a transition in the HSM and process it synchronously.
 
voidtransitionWithQueueClear (const EventID_t event, Args&&... args)
 Trigger a transition in the HSM and clear all pending events.
 
booltransitionInterruptSafe (const EventID_t event)
 Interrupt/signal safe version of transition.
 
boolisTransitionPossible (const EventID_t event, Args&&... args)
 Check if a transition is possible.
 
voidstartTimer (const TimerID_t timerID, const unsigned int intervalMs, const bool isSingleShot)
 Start a timer.
 
voidrestartTimer (const TimerID_t timerID)
 Restart running timer.
 
voidstopTimer (const TimerID_t timerID)
 Stop active timer.
 
boolisTimerRunning (const TimerID_t timerID)
 Check if timer is currently running.
 
boolenableHsmDebugging ()
 Enable debugging for HSM instance.
 
boolenableHsmDebugging (const std::string &dumpPath)
 Enable debugging for HSM instance with specific path for the log file. Enables creation of the log file that can be later analyzed with hsmdebugger.
 
voiddisableHsmDebugging ()
 Disable HSM debugging.
 

Class Documentation

class HierarchicalStateMachine

Implements a Hierarchical State Machine (HSM) for event-driven systems.

Represents a hierarchical state machine (HSM) with a set of states and state transitions. This class allows for the creation and manipulation of a state machine, where the HSM can be in one of a finite set of states, and can transition between states based on a set of defined rules. The HSM can have multiple levels of nested states and transitions can be defined between any two states, including self-transitions. The class provides public functions to:

  • define state machine structure

  • define transition rules

  • register state and transition callbacks

  • trigger state transitions

  • interact with HSM timers

Public Functions


explicit HierarchicalStateMachine(const StateID_t initialState)

Constructor that sets the initial state of the HSM.

Initial state can be modified later with setInitialState().

Parameters

initialState – The initial state of the HSM.


virtual ~HierarchicalStateMachine()

Destructor.

Not Thread Safe

Internally uses release().


void setInitialState(const StateID_t initialState)

Sets the initial state of the HSM.

Concurrency

thread-safe, interrupt-safe

Remark

Has no effect when called after initialize().

Parameters

initialState – The initial state of the HSM.


virtual bool initialize(const std::weak_ptr<IHsmEventDispatcher> &dispatcher)

Initializes the HSM.

Registers HSM with provided event dispatcher and transitions state machine into it’s initial state. HSM structure must be registered BEFORE calling it. Changing structure after this call can result in undefined behavior and is not advised.

Not Thread Safe

Internally uses IHsmEventDispatcher::registerEventHandler() and IHsmEventDispatcher::start(). Usually must be called from the same thread where dispatcher was created.

Remark

If initial state has registered callbacks or actions they will be executed synchronously during initialize() call.

Warning

HSM does not take ownership of the dispatcher. User is responsible for keeping dispatcher instance alive as long as HSM object exists or until call to release().

Parameters

dispatcher – An event dispatcher that can be used to receive events and dispatch them to the HSM.

Returns

true if initialization succeeds, false otherwise.


std::weak_ptr<IHsmEventDispatcher> dispatcher() const

Returns dispatcher that was passed to initialize() method.

Concurrency

thread-safe

Returns

dispatcher used by HSM or nullptr (if HSM was not initialized or release() was called).


bool isInitialized() const

Checks initialization status of HSM.

Concurrency

thread-safe, interrupt-safe

Return values
  • true – HSM is initialized

  • false – HSM is not initialized


void release()

Releases dispatcher instance and frees any allocated internal resources.

Internally calls IHsmEventDispatcher::unregisterEventHandler(). Usually, HSM has to be released on the same thread it was initialized.

Not Thread Safe

Usually must be called on the same thread as initialize(). Releases reference to dispatcher. In case HierarchicalStateMachine object is the only one owning IHsmEventDispatcher reference, then you need to check the limitations for deleting dispatcher instance. See the documentation for the used dispatcher.

Note

Usually you don’t need to call this function directly. The only scenario when it’s needed is for multithreaded environment where it’s impossible to delete HSM instance on the same thread where it was initialized. In this case you call release() on the dispatcher’s thread before deleting HSM instance on another thread.

Warning

HSM can’t be reused after calling this API.


void registerFailedTransitionCallback(HsmTransitionFailedCallback_t onFailedTransition)

Registers a callback function to be called when a transition fails.

Transition failure is usually caused by:

  • no defined transition from the current active state for triggered event

  • false conditions for all matching transitions

  • transition was blocked by exit or enter callback returning false

Concurrency

thread-safe, interrupt-safe

Parameters

onFailedTransition – The callback function to be called when transition fails.


template<class HsmHandlerClass>
void registerFailedTransitionCallback(HsmHandlerClass *handler, void (HsmHandlerClass::* onFailedTransition)(const std::list<StateID_t>&, const EventID_t, const VariantVector_t&))

Registers a class member as a callback function to be called when a transition fails.

Transition failure is usually caused by:

  • no defined transition from the current active state for triggered event

  • false conditions for all matching transitions

  • transition was blocked by exit or enter callback returning false

Concurrency

thread-safe, interrupt-safe

Parameters
  • onFailedTransition – The callback function to be called when transition fails.

  • handler – Pointer to an object whose class members will be used as callbacks.


void registerState(const StateID_t state, HsmStateChangedCallback_t onStateChanged = nullptr, HsmStateEnterCallback_t onEntering = nullptr, HsmStateExitCallback_t onExiting = nullptr)

Registers a new state and optional state callbacks.

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Parameters
  • state – unique ID of the state to be registered.

  • onStateChanged – (optional) callback function to be called when the state became active.

  • onEntering – (optional) callback function to be called when entering the state.

  • onExiting – (optional) callback function to be called before exiting the state.


template<class HsmHandlerClass>
void registerState(const StateID_t state, HsmHandlerClass *handler = nullptr, void (HsmHandlerClass::* onStateChanged)(const VariantVector_t&) = nullptr, bool (HsmHandlerClass::* onEntering)(const VariantVector_t&) = nullptr, bool (HsmHandlerClass::* onExiting)() = nullptr)

Registers a new state and optional state callbacks (using class members).

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Warning

If handler object is destroyed while HSM instance is still running it will result in a crash.

Parameters
  • state – unique ID of the state to be registered.

  • onStateChanged – (optional) callback function to be called when the state became active.

  • onEntering – (optional) callback function to be called when entering the state.

  • onExiting – (optional) callback function to be called before exiting the state.

Template Parameters

handler – Pointer to an object whose class members will be used as callbacks.


void registerFinalState(const StateID_t state, const EventID_t event = INVALID_HSM_EVENT_ID, HsmStateChangedCallback_t onStateChanged = nullptr, HsmStateEnterCallback_t onEntering = nullptr, HsmStateExitCallback_t onExiting = nullptr)

Registers state as final.

See Final State for details.

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Parameters
  • state – unique ID of the state to be registered as final.

  • event – (optional) event ID to automatically trigger when entering a final state. If not set (INVALID_HSM_EVENT_ID value is used) then HSM will trigger same event which was used to transition into this final state.

  • onStateChanged – (optional) callback function to be called when the state became active.

  • onEntering – (optional) callback function to be called when entering the state.

  • onExiting – (optional) callback function to be called before exiting the state.


template<class HsmHandlerClass>
void registerFinalState(const StateID_t state, const EventID_t event = INVALID_HSM_EVENT_ID, HsmHandlerClass *handler = nullptr, void (HsmHandlerClass::* onStateChanged)(const VariantVector_t&) = nullptr, bool (HsmHandlerClass::* onEntering)(const VariantVector_t&) = nullptr, bool (HsmHandlerClass::* onExiting)() = nullptr)

Registers a state as final using class members as callbacks.

See Final State for details.

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Warning

If handler object is destroyed while HSM instance is still running it will result in a crash.

Parameters
  • state – unique ID of the state to be registered as final.

  • event – (optional) event ID to automatically trigger when entering a final state. If not set (INVALID_HSM_EVENT_ID value is used) then HSM will trigger same event which was used to transition into this final state.

  • onStateChanged – (optional) callback function to be called when the state became active.

  • onEntering – (optional) callback function to be called when entering the state.

  • onExiting – (optional) callback function to be called before exiting the state.

  • handler – Pointer to an object whose class members will be used as callbacks.


void registerHistory(const StateID_t parent, const StateID_t historyState, const HistoryType type = HistoryType::SHALLOW, const StateID_t defaultTarget = INVALID_HSM_STATE_ID, HsmTransitionCallback_t transitionCallback = nullptr)

Registers a history state with the state machine.

See History for details.

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Parameters
  • parent – ID of the parent state.

  • historyState – ID of the state to be registered as history state.

  • type – type of history to be used.

  • defaultTarget – ID of the default target state to be used when transitioning into empty history state.

  • transitionCallback – transition callback function to be called when the history state is entered.


template<class HsmHandlerClass>
void registerHistory(const StateID_t parent, const StateID_t historyState, const HistoryType type = HistoryType::SHALLOW, const StateID_t defaultTarget = INVALID_HSM_STATE_ID, HsmHandlerClass *handler = nullptr, void (HsmHandlerClass::* transitionCallback)(const VariantVector_t&) = nullptr)

Registers a history state with the state machine (using class member as a callback)

See History for details.

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Warning

If handler object is destroyed while HSM instance is still running it will result in a crash.

Parameters
  • parent – ID of the parent state.

  • historyState – ID of the state to be registered as history state.

  • type – type of history to be used.

  • defaultTarget – ID of the default target state to be used when transitioning into empty history state.

  • transitionCallback – transition callback function to be called when the history state is entered.

  • handler – Pointer to an object whose class members will be used as callbacks.


bool registerSubstate(const StateID_t parent, const StateID_t substate)

Registers state as a substate.

Substate must be first registered with a call to registerState(). HSM will make a sanity structure check if HSM_ENABLE_SAFE_STRUCTURE. Following cases are not allowed:

  • parent and substate can’t be same

  • substate can’t belong to multiple parents

  • circular dependencies are not allowed (A -> B -> A -> …) See Substates for details.

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Parameters
  • parent – ID of the parent state.

  • substate – ID of the state to be registered as substate

Return values
  • true – substate was successfully registered

  • false – registering substate is not allowed


bool registerSubstateEntryPoint(const StateID_t parent, const StateID_t substate, const EventID_t onEvent = INVALID_HSM_EVENT_ID, HsmTransitionConditionCallback_t conditionCallback = nullptr, const bool expectedConditionValue = true)

Registers an entry point for a parent state.

Entry point state must be first registered with a call to registerState(). HSM will make a sanity structure check if HSM_ENABLE_SAFE_STRUCTURE. Following cases are not allowed:

  • parent and entry point can’t be same

  • entry point can’t belong to multiple parents

  • circular dependencies are not allowed (A -> B -> A -> …) See Entry Points for details.

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Parameters
  • parent – ID of the parent state.

  • substate – ID of the substate to be registered as an entry point.

  • onEvent – (optional) ID of the event that should match event that caused activation of the parent state.

  • conditionCallback – (optional) callback function that will be called to determine if the transition to the entry point is allowed or not.

  • expectedConditionValue – (optional) expected value from the condition callback to allow transition to the entry state.

Return values
  • true – substate was successfully registered

  • false – registering substate is not allowed


template<class HsmHandlerClass>
bool registerSubstateEntryPoint(const StateID_t parent, const StateID_t substate, const EventID_t onEvent = INVALID_HSM_EVENT_ID, HsmHandlerClass *handler = nullptr, bool (HsmHandlerClass::* conditionCallback)(const VariantVector_t&) = nullptr, const bool expectedConditionValue = true)

Registers an entry point for a parent state with class member as a callback.

Entry point state must be first registered with a call to registerState(). HSM will make a sanity structure check if HSM_ENABLE_SAFE_STRUCTURE. Following cases are not allowed:

  • parent and entry point can’t be same

  • entry point can’t belong to multiple parents

  • circular dependencies are not allowed (A -> B -> A -> …) See Entry Points for details.

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Warning

If handler object is destroyed while HSM instance is still running it will result in a crash.

Parameters
  • parent – ID of the parent state.

  • substate – ID of the substate to be registered as an entry point.

  • onEvent – (optional) ID of the event that should match event that caused activation of the parent state.

  • conditionCallback – (optional) callback function that will be called to determine if the transition to the entry point is allowed or not.

  • expectedConditionValue – (optional) expected value from the condition callback to allow transition to the entry state.

  • handler – Pointer to an object whose class members will be used as callbacks.

Return values
  • true – substate was successfully registered

  • false – registering substate is not allowed


void registerTimer(const TimerID_t timerID, const EventID_t event)

Registers a timer to be used inside HSM.

This function registers new timer and it’s event. When the timer expires, the event is sent to the state machine.

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Parameters
  • timerID – unique ID of the timer.

  • event – ID of the event to send when timer expires.


template<typename ...Args>
bool registerStateAction(const StateID_t state, const StateActionTrigger actionTrigger, const StateAction action, Args&&... args)

Registers a state action with optional arguments.

The action will be triggered depending on the specified action trigger when the state is activated. See State actions for details.

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Parameters
  • state – ID of the state for actions are being registered.

  • actionTrigger – trigger for the state action.

  • action – action type to register.

  • args – optional arguments for the state action (see StateAction enum for details).

Return values
  • true – state action was registered

  • false – action registration failed due to invalid arguments


void registerTransition(const StateID_t fromState, const StateID_t toState, const EventID_t onEvent, HsmTransitionCallback_t transitionCallback = nullptr, HsmTransitionConditionCallback_t conditionCallback = nullptr, const bool expectedConditionValue = true)

Registers a transition from one state to another.

The transition will be triggered by the specified event when the from state is active. See Transitions for details.

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Parameters
  • from – ID of the state to transition from.

  • to – ID of the state to transition to.

  • onEvent – ID of the event that triggers the transition.

  • transitionCallback – (optional) callback function that will be called when transition occurs.

  • conditionCallback – (optional) callback function that will be called to determine if the transition is allowed.

  • expectedConditionValue – (optional) expected value from the condition callback function to allow transition.


template<class HsmHandlerClass>
void registerTransition(const StateID_t fromState, const StateID_t toState, const EventID_t onEvent, HsmHandlerClass *handler = nullptr, void (HsmHandlerClass::* transitionCallback)(const VariantVector_t&) = nullptr, bool (HsmHandlerClass::* conditionCallback)(const VariantVector_t&) = nullptr, const bool expectedConditionValue = true)

Registers a transition from one state to another.

The transition will be triggered by the specified event when the from state is active. See Transitions for details.

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Warning

If handler object is destroyed while HSM instance is still running it will result in a crash.

Parameters
  • from – ID of the state to transition from.

  • to – ID of the state to transition to.

  • onEvent – ID of the event that triggers the transition.

  • transitionCallback – (optional) callback function that will be called when transition occurs.

  • conditionCallback – (optional) callback function that will be called to determine if the transition is allowed.

  • expectedConditionValue – (optional) expected value from the condition callback function to allow transition.

  • handler – Pointer to an object whose class members will be used as callbacks.


void registerSelfTransition(const StateID_t state, const EventID_t onEvent, const TransitionType type = TransitionType::EXTERNAL_TRANSITION, HsmTransitionCallback_t transitionCallback = nullptr, HsmTransitionConditionCallback_t conditionCallback = nullptr, const bool expectedConditionValue = true)

Register a self-transition for a state.

This function registers a self-transition for a given state. A self-transition is a transition from a state to itself, triggered by a specific event. The transition can be either internal or external. The user can also register a transition callback and a transition condition callback. See Self transitions for details.

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Parameters
  • state – ID of the state to register self-transition for

  • onEvent – ID of event that triggers self-transition

  • type – type of self transition

  • transitionCallback – A function that is called when the transition occurs (default: nullptr).

  • conditionCallback – A function that is called to determine if the transition is allowed (default: nullptr).

  • expectedConditionValue – The expected value returned by the condition callback (default: true).


template<class HsmHandlerClass>
void registerSelfTransition(const StateID_t state, const EventID_t onEvent, const TransitionType type = TransitionType::EXTERNAL_TRANSITION, HsmHandlerClass *handler = nullptr, void (HsmHandlerClass::* transitionCallback)(const VariantVector_t&) = nullptr, bool (HsmHandlerClass::* conditionCallback)(const VariantVector_t&) = nullptr, const bool expectedConditionValue = true)

Register a self-transition for a state (using class members as callback).

This function registers a self-transition for a given state. A self-transition is a transition from a state to itself, triggered by a specific event. The transition can be either internal or external. The user can also register a transition callback and a transition condition callback. See Self transitions for details.

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Warning

If handler object is destroyed while HSM instance is still running it will result in a crash.

Parameters
  • state – ID of the state to register self-transition for

  • onEvent – ID of event that triggers self-transition

  • type – type of self transition

  • transitionCallback – A function that is called when the transition occurs (default: nullptr).

  • conditionCallback – A function that is called to determine if the transition is allowed (default: nullptr).

  • expectedConditionValue – The expected value returned by the condition callback (default: true).

  • handler – Pointer to an object whose class members will be used as callbacks.


StateID_t getLastActiveState() const

Get the ID of the last activated state.

Returns current active state if HSM doesn’t contain any parallel states. Otherwise returns most recently activated state.

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Returns

ID of the last active state.


const std::list<StateID_t> &getActiveStates() const

Get the list of currently active states.

Returns

list of currently active states.


bool isStateActive(const StateID_t state) const

Check if a state is active.

This function checks if a specific state is currently active in the HSM.

Parameters

state – ID of the state to check

Returns

True if the state is active, false otherwise.


template<typename ...Args>
void transition(const EventID_t event, Args&&... args)

Trigger a transition in the HSM.

This function sends event to HSM to trigger a potential transition. The transition is executed asynchronously, and any registered callbacks are called in the order they were registered. The user can optionally provide arguments which will be passed to all callbacks triggered by transition.

Concurrency

thread-safe

Parameters
  • event – ID of event to send to HSM

  • args – (optional) arguments to pass to the callbacks


template<typename ...Args>
bool transitionEx(const EventID_t event, const bool clearQueue, const bool sync, const int timeoutMs, Args&&... args)

Trigger a transition in the HSM.

This is an extended version of transition() function. It also allows to sends an event to HSM to trigger a potential transition, but provides a bit more capabilities.

Concurrency

thread-safe

Warning

setting sync=true when calling this function from HSM callback will result in blocking HSM events processing and will result in a deadlock if timeoutMs is set to HSM_WAIT_INDEFINITELY.

Parameters
  • event – ID of event to send to HSM

  • clearQueue – indicates whether to clear the pending events queue before adding a new event

  • sync – indicates whether to wait for the transition to complete before returning. Keep in mind that this does not cancel transition if it couldn’t finish before timeoutMs. If you need to guarantee that transition was fully processed make sure to set timeoutMs to HSM_WAIT_INDEFINITELY.

  • timeoutMs – maximum time in milliseconds to wait for the transition to complete if sync is true. Use HSM_WAIT_INDEFINITELY to wait indefinitely.

  • args – (optional) arguments to pass to the callbacks

Return values
  • true – (if sync=true) event was accepted and transition successfully finished

  • false – (if sync=true) no matching transitions were found, transition was canceled or timeoutMs expired

Returns

always returns true if sync=false.


void transitionWithArgsArray(const EventID_t event, VariantVector_t &&args)

Trigger a transition in the HSM with arguments passed as a vector.

This function sends event to HSM to trigger a potential transition. The transition is executed asynchronously, and any registered callbacks are called in the order they were registered. The user can optionally provide arguments which will be passed to all callbacks triggered by transition.

Concurrency

thread-safe

Parameters
  • event – ID of event to send to HSM

  • args – (optional) arguments to pass to the callbacks


bool transitionExWithArgsArray(const EventID_t event, const bool clearQueue, const bool sync, const int timeoutMs, VariantVector_t &&args)

Trigger a transition in the HSM with arguments passed as a vector.

This is an extended version of transition() function. It also allows to sends an event to HSM to trigger a potential transition, but provides a bit more capabilities.

Concurrency

thread-safe

Warning

setting sync=true when calling this function from HSM callback will result in blocking HSM events processing and will result in a deadlock if timeoutMs is set to HSM_WAIT_INDEFINITELY.

Parameters
  • event – ID of event to send to HSM

  • clearQueue – indicates whether to clear the pending events queue before adding a new event

  • sync – indicates whether to wait for the transition to complete before returning. Keep in mind that this does not cancel transition if it couldn’t finish before timeoutMs. If you need to guarantee that transition was fully processed make sure to set timeoutMs to HSM_WAIT_INDEFINITELY.

  • timeoutMs – maximum time in milliseconds to wait for the transition to complete if sync is true. Use HSM_WAIT_INDEFINITELY to wait indefinitely.

  • args – (optional) arguments to pass to the callbacks

Return values
  • true – (if sync=true) event was accepted and transition successfully finished

  • false – (if sync=true) no matching transitions were found, transition was canceled or timeoutMs expired

Returns

always returns true if sync=false.


template<typename ...Args>
bool transitionSync(const EventID_t event, const int timeoutMs, Args&&... args)

Trigger a transition in the HSM and process it synchronously.

Convenience wrapper for transitionEx() which tries to execute transition synchronously. Please see transitionEx() for detailed description.

Concurrency

thread-safe

Warning

calling this function from HSM callback might result in a deadlock (see transitionEx() for details).

Parameters
  • event – ID of event to send to HSM

  • timeoutMs – maximum time in milliseconds to wait for the transition to complete if sync is true. Use HSM_WAIT_INDEFINITELY to wait indefinitely.

  • args – (optional) arguments to pass to the callbacks

Return values
  • true – event was accepted and transition successfully finished

  • false – no matching transitions were found, transition was canceled or timeoutMs expired


template<typename ...Args>
void transitionWithQueueClear(const EventID_t event, Args&&... args)

Trigger a transition in the HSM and clear all pending events.

Convenience wrapper for transitionEx() which clears the pending events queue before sending a new event. Transition is executed asynchronously.

Concurrency

thread-safe

Parameters
  • event – ID of event to send to HSM

  • args – (optional) arguments to pass to the callbacks


bool transitionInterruptSafe(const EventID_t event)

Interrupt/signal safe version of transition.

This is a simplified version of transition that can be safely used from an interrupt/signal. Event is processed asynchronously.

Concurrency

thread-safe, interrupt-safe

Remark

There are no restrictions to use other transition APIs inside an interrupt, but all of them use dynamic heap memory allocation (which can cause heap corruption on some platfroms). This version of the transition relies on dispatcher implementation and might not be available everywhere (please check dispatcher’s description). It also might fail if internal dispatcher events queue is full.

Parameters

event – ID of event to send to HSM

Return values
  • true – event was added to queue

  • false – failed to add event to queue because it’s not supported by dispatcher or queue limit was reached


template<typename ...Args>
bool isTransitionPossible(const EventID_t event, Args&&... args)

Check if a transition is possible.

This function checks if a transition can be triggered by the given event and current state. This function takes a variable number of arguments, which will be passed to the condition callbacks of the relevant states and transitions.

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Remark

It’s recommended to avoid using this API unless really needed. It might confuse in a multithreaded environment since it only can check possibility of transition in the current HSM state, but it can’t prevent this state from changing after returning from isTransitionPossible(). You would have to use additional synchronization mechanisms to guarantee that state doesn’t change between calls to isTransitionPossible() and transition().

Parameters
  • event – ID of event to send to HSM

  • args – (optional) arguments to pass to the condition callbacks

Returns

True if a transition is possible, false otherwise.


void startTimer(const TimerID_t timerID, const unsigned int intervalMs, const bool isSingleShot)

Start a timer.

If timer with this ID is already running it will be restarted with new settings.

Concurrency

thread-safe

Parameters
  • timerID – unique timer id

  • intervalMs – timer interval in milliseconds

  • isSingleShot – true - timer will run only once and then will stop false - timer will keep running until stopTimer() is called or dispatcher is destroyed


void restartTimer(const TimerID_t timerID)

Restart running timer.

Timer is restarted with the same arguments which were provided to startTimer(). Only currently running or expired timers (with isSingleShot set to true) will be restarted. Has no effect if called for a timer which was not started.

Concurrency

thread-safe

Parameters

timerID – id of running timer


void stopTimer(const TimerID_t timerID)

Stop active timer.

Function stops an active timer without triggering any notifications and unregisters it. Further calls to restartTimer() will have no effects untill it’s started again with startTimer().

Concurrency

thread-safe

Remark

For expired timers (which have isSingleShot property set to true), funtion simply unregisters them.

Parameters

timerID – id of running or expired timer


bool isTimerRunning(const TimerID_t timerID)

Check if timer is currently running.

Concurrency

thread-safe

Parameters

timerID – id of the timer to check

Return values
  • true – timer is running

  • false – timer is not running


bool enableHsmDebugging()

Enable debugging for HSM instance.

Enables creation of the log file that can be later analyzed with hsmdebugger. By default log will be written to ./dump.hsmlog file. This location can be overwritten by setting ENV_DUMPPATH environment variable with desired path.

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Remark

HSMBUILD_DEBUGGING build option must be enabled for this functionality to work. It’s recommended to keep this feature disabled in production code to avoid performance overhead.

Return values
  • true – debugging was successfully enabled

  • false – failed to open log file


bool enableHsmDebugging(const std::string &dumpPath)

Enable debugging for HSM instance with specific path for the log file. Enables creation of the log file that can be later analyzed with hsmdebugger.

Not Thread Safe

Calling thing API from multiple threads can cause data races and will result in undefined behavior

Remark

HSMBUILD_DEBUGGING build option must be enabled for this functionality to work. It’s recommended to keep this feature disabled in production code to avoid performance overhead.

Parameters

dumpPath – The path for the dump files.

Return values
  • true – debugging was successfully enabled (always returns true if HSMBUILD_DEBUGGING was not set)

  • false – failed to open log file


void disableHsmDebugging()

Disable HSM debugging.

This function disables debugging for the Hierarchical State Machine and closes the log file. Does nothing if enableHsmDebugging() was not called.

Concurrency

thread-safe

Internally just calls std::filebuf::close().