有限状态机
有限状态机
State Machine design pattern prevents you from creating and maintaining spaghetti code.
简介
略
State Machine Language/Lite/Library
实践
代码结构
├── CMakeLists.txt
├── launch
│ └── sml_test_node.launch
├── package.xml
├── param
│ └── sml_test_node.yaml
├── README.md
└── src
├── boost
│ ├── sml
│ └── sml.hpp
├── fsm.h
├── main.cc
├── node.cc
├── node.h
├── processor.cc
├── processor.h
└── util
├── guardian_fsm.h
└── log_helper.h
代码实践
- fsm.h
#ifndef FSM_H_
#define FSM_H_
namespace ericeric {
class FSM {
public:
virtual ~FSM() = default;
bool on_start() {return true;};
bool on_error() {return false;};
bool on_lock() {return false;};
bool on_unlock() {return false;};
bool on_resume() {return false;};
};
} // namespace ericeric
#endif // FSM_H_
- util/guardian_fsm.h
#ifndef GUARDIAN_FSM_H_
#define GUARDIAN_FSM_H_
#include "../boost/sml.hpp"
#include "fsm.h"
namespace ericeric {
namespace sml = boost::sml;
// state
struct WaitActive {};
struct Active {};
struct Inactive {};
struct Error {};
// event、transition
struct ev_start {};
struct ev_error {};
struct ev_resume {};
struct ev_lock {};
struct ev_unlock {};
// guards、transition condition
const auto onStart = [](FSM* fsm) { return fsm->on_start(); };
const auto onError = [](FSM* fsm) { return fsm->on_error(); };
const auto onLock = [](FSM* fsm) { return fsm->on_lock(); };
const auto onUnlock = [](FSM* fsm) { return fsm->on_unlock(); };
const auto onResume = [](FSM* fsm) { return fsm->on_resume(); };
// 定义状态机
struct FsmGuardian {
auto operator()() const {
using namespace sml;
// clang-format off
return make_transition_table(
* state<WaitActive> + event<ev_start> [onStart] = state<Active>
, state<Active> + event<ev_error> / onError = state<Error>
, state<Active> + event<ev_lock> / onLock = state<Inactive>
, state<Inactive> + event<ev_unlock> / onUnlock = state<Active>
, state<Error> + event<ev_resume> / onResume = state<Active>
);
// clang-format on
}
};
} // namespace ericeric
#endif // GUARDIAN_FSM_H_