您可以使用在 c 中实现的极简主义uml-state-machine 框架。它支持有限和分层状态机。该框架非常简约。它只有 3 个 API、2 个结构和 1 个枚举。
状态机由state_machine_t 结构表示。它是一种抽象结构,可以被继承来创建状态机。
//! Abstract state machine structure
struct state_machine_t
{
uint32_t Event; //!< Pending Event for state machine
const state_t* State; //!< State of state machine.
};
状态由指向框架中state_t结构的指针表示。
如果框架配置为有限状态机,则state_t 包含,
typedef struct finite_state_t state_t;
// finite state structure
typedef struct finite_state_t{
state_handler Handler; //!< State handler function (function pointer)
state_handler Entry; //!< Entry action for state (function pointer)
state_handler Exit; //!< Exit action for state (function pointer)
}finite_state_t;
如果框架配置为支持分层状态机。它包含额外的三个成员来表示状态之间的层次关系。
typedef struct hierarchical_state_t state_t;
//! Hierarchical state structure
typedef struct hierarchical_state_t
{
state_handler Handler; //!< State handler function
state_handler Entry; //!< Entry action for state
state_handler Exit; //!< Exit action for state.
const state_t* const Parent; //!< Parent state of the current state.
const state_t* const Node; //!< Child states of the current state.
uint32_t Level; //!< Hierarchy level from the top state.
}hierarchical_state_t;
框架提供了一个 API dispatch_event 将事件分派到状态机和两个用于状态遍历的 API。
state_machine_result_t dispatch_event(state_machine_t* const pState_Machine[], uint32_t quantity);
state_machine_result_t switch_state(state_machine_t* const pState_Machine, const state_t* pTarget_State);
state_machine_result_t traverse_state(state_machine_t* const pState_Machine, const state_t* pTarget_State);
更多详情请参考GitHub项目。