State Machine

[中文]

Public header: #include "brookesia/lib_utils/state_machine.hpp"

Overview

state_machine implements registration, actions, transition callbacks, and runtime control for multi-state workflows.

Features

  • Add states and transition rules

  • Initial state and forced switches

  • Transition callbacks and runtime queries

  • Optional integration with TaskScheduler for async work

API Reference

Header File

Classes

class StateMachine

Thread-safe Finite State Machine implementation.

Manages states, transitions, and state lifecycle with support for:

  • State entry/exit guards (on_enter/on_exit)

  • Periodic state updates (on_update)

  • State timeouts with automatic action triggering

  • Asynchronous state transitions via action queue

  • Serial execution guarantee (no concurrent state transitions)

  • Transition rollback on entry failure

Note

All state transitions are executed serially through the task scheduler’s group mechanism, ensuring thread-safe operations even when actions are triggered from multiple threads. State callbacks (on_enter, on_exit, on_update) are executed without holding internal locks, allowing them to safely trigger new actions or perform blocking operations.

Public Types

using StatePtr = std::shared_ptr<StateBase>

Shared pointer type used for registered states.

using TransitionFinishCallback = std::function<void(const std::string &from, const std::string &action, const std::string &to)>

Callback type invoked after a transition completes successfully.

Public Functions

StateMachine() = default

Constructor.

~StateMachine()

Stop the state machine and release owned resources.

bool add_state(StatePtr state)

Register a named state object.

Parameters

state – Shared pointer to the state implementation.

Returns

true if the state was added, or false when a state with the same name already exists.

bool add_transition(const std::string &from, const std::string &action, const std::string &to)

Register a transition between two states.

Parameters
  • from – Source state name.

  • action – Action name that triggers the transition.

  • to – Target state name.

Returns

true if the transition was added, or false when the same (from, action) mapping already exists.

bool start(Config config)

Start the state machine and enter the initial state.

Note

If the state machine is already running, this returns true immediately. If the scheduler is not running, this will attempt to start it. The task group is automatically configured for serial execution to ensure thread-safe transitions.

Parameters

config – Configuration for the state machine.

Returns

true on success, or false if the initial state cannot be entered or startup fails.

void stop()

Stop the state machine and wait for pending scheduled work to finish.

Note

This method is thread-safe and can be called multiple times safely. It will wait for all pending state tasks to complete before returning.

bool trigger_action(const std::string &action, bool use_dispatch = false)

Queue or dispatch a transition action.

Note

The actual transition happens asynchronously in the task scheduler’s serial queue. This ensures thread-safe state transitions even when called from multiple threads.

Parameters
Returns

true if the action was scheduled successfully, or false otherwise.

bool wait_all_transitions(uint32_t timeout_ms)

Wait until no transitions are queued or running.

Parameters

timeout_ms – Timeout in milliseconds. The special value static_cast<uint32_t>(-1) waits indefinitely.

Returns

true if all transitions completed before the timeout, or false otherwise.

bool force_transition_to(const std::string &target_state)

Cancel scheduled state tasks and overwrite the current state name immediately.

Note

This bypasses on_exit(), on_enter(), timeout scheduling, periodic updates, and transition callbacks.

Parameters

target_state – State name assigned as the new current state.

Returns

true once the internal state name has been updated.

inline void register_transition_finish_callback(TransitionFinishCallback callback)

Register a callback invoked after a successful transition.

Note

The callback is invoked with (from_state, action, to_state) parameters. The callback will be executed without holding internal locks, so it’s safe to perform any operations including triggering new actions.

Parameters

callback – Callback invoked with (from_state, action, to_state).

inline bool is_running() const

Check whether the state machine has been started.

Note

This method is thread-safe.

Returns

true when the machine owns a scheduler and is running, or false otherwise.

inline bool has_transition_running() const

Check whether any transitions are queued or currently executing.

Note

This method is thread-safe.

Returns

true when one or more transitions are pending or in progress, or false otherwise.

inline bool has_state_updating() const

Check whether the current state has an active periodic update task.

Note

This method is thread-safe.

Returns

true when a periodic update task is installed, or false otherwise.

inline std::string get_current_state() const

Get the name of the current state.

Note

This method is thread-safe and returns a copy of the state name.

Returns

Current state name, or an empty string when the machine has not started.

inline StatePtr get_state_ptr(const std::string &name) const

Look up a registered state by name.

Note

This method is thread-safe.

Parameters

name – State name to look up.

Returns

Shared pointer to the registered state, or nullptr if not found.

Public Static Attributes

static constexpr const char *DEFAULT_TASK_GROUP_NAME = "state_machine"

Default scheduler group name used by the state machine.

struct Config

Configuration for the state machine.

Public Members

std::shared_ptr<TaskScheduler> task_scheduler

Task scheduler used to serialize transitions, timeouts, and periodic updates.

std::string task_group_name = DEFAULT_TASK_GROUP_NAME

Task group name used for serialized state-machine tasks.

TaskScheduler::GroupConfig task_group_config  = {.enable_serial_execution = true,}

Task group configuration.

std::string initial_state

Initial state name.