状态机

[English]

公共头文件: #include "brookesia/lib_utils/state_machine.hpp"

概述

state_machine 提供状态机实现,支持状态注册、动作触发、转换回调与运行时控制, 适合管理复杂流程与多状态切换场景。

特性

  • 支持添加状态与状态转换规则

  • 支持指定初始状态与强制切换

  • 支持转换完成回调与运行状态查询

  • 可与 TaskScheduler 联动进行异步调度

API 参考

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

备注

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.

参数

state – Shared pointer to the state implementation.

返回

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.

参数
  • from – Source state name.

  • action – Action name that triggers the transition.

  • to – Target state name.

返回

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.

备注

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.

参数

config – Configuration for the state machine.

返回

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.

备注

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.

备注

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

参数
返回

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.

参数

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

返回

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.

备注

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

参数

target_state – State name assigned as the new current state.

返回

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.

备注

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.

参数

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

inline bool is_running() const

Check whether the state machine has been started.

备注

This method is thread-safe.

返回

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.

备注

This method is thread-safe.

返回

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.

备注

This method is thread-safe.

返回

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.

备注

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

返回

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.

备注

This method is thread-safe.

参数

name – State name to look up.

返回

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.