enum class FoodEventType {
FET_LOGIN, // 开始登陆
FET_LOGIN_FAILED, // 登陆失败
FET_LOGIN_OK, // 登陆成功
FET_LOGOUT, // 登出
class FoodEvent : public kuafu::EventTemplate<FoodEventType> {
public:
using underlying_type = std::underlying_type<FoodEventType>::type;
FoodEvent(FoodEventType type, const kuafu::MachineBaseSharedPtr& machine)
:kuafu::EventTemplate<FoodEventType>(type, machine) {
};
class FoodMachine : public kuafu::StateMachine {
public:
FoodMachine(const std::string& name);
public:
virtual void Birth();
public:
// 需要用到的三种状态: 启动, 登陆中, 成功
kuafu::StateSharedPtr startup_;
kuafu::StateSharedPtr loging_;
kuafu::StateSharedPtr welcome_;
// 需要用到的几种转换
kuafu::TransitionSharedPtr startup_loging_;
kuafu::TransitionSharedPtr loging_welcome_;
kuafu::TransitionSharedPtr loging_startup_;
kuafu::TransitionSharedPtr welcome_startup_;
kuafu::TransitionSharedPtr welcome_timeout_;
};
void FoodMachine::Birth() {
startup_ = kuafu::State::MakeState(*this, "startup");
loging_ = kuafu::State::MakeState(*this, "loging");
welcome_ = kuafu::State::MakeState(*this, "welcom", 5000);
startup_loging_ = kuafu::Transition::MakeTransition("startup_loging",
startup_,
loging_,
std::make_shared<kuafu::SimplePredicate<FoodEvent>>(FoodEventType::FET_LOGIN));
loging_welcome_ = kuafu::Transition::MakeTransition("loging_welcome",
loging_,
welcome_,
std::make_shared<kuafu::SimplePredicate<FoodEvent>>(FoodEventType::FET_LOGIN_OK));
loging_startup_ = kuafu::Transition::MakeTransition("loging_startup",
loging_,
startup_,
std::make_shared<kuafu::SimplePredicate<FoodEvent>>(FoodEventType::FET_LOGIN_FAILED));
welcome_startup_ = kuafu::Transition::MakeTransition("welcome_startup",
welcome_,
startup_,
std::make_shared<kuafu::SimplePredicate<FoodEvent>>(FoodEventType::FET_LOGOUT));
welcome_timeout_ = kuafu::Transition::MakeTransition("welcome_timeout",
welcome_,
welcome_,
std::make_shared<kuafu::TimeoutPredicate>(type_));
}
food_machine->startup_->OnEnter = [&](kuafu::MachineBase& machine,
const kuafu::StateSharedPtr& state) {
INFO_LOG("Enter " << state->GetName());
food_machine->startup_loging_->OnTransition = [&](kuafu::MachineBase& machine,
const kuafu::StateSharedPtr& from_state,
kuafu::ITransitionSharedPtr transition,
kuafu::EventSharedPtr event,
const kuafu::StateSharedPtr& to_state) {
INFO_LOG(transition->GetName()
<< " | "
<< from_state->GetName()
<< " -> "
<< to_state->GetName());
...
machine_set->Enqueue(std::make_shared<kuafu::MachineOperationEvent>(
kuafu::MachineOperator::MO_ADD,
food_machine));
machine_set->Enqueue(std::make_shared<FoodEvent>(
FoodEventType::FET_LOGIN,
food_machine));