#include <iostream>
#include <boost/msm/back/state_machine.hpp>
#include <boost/msm/front/state_machine_def.hpp>
#include <boost/msm/front/functor_row.hpp>
namespace msm = boost::msm;
namespace mpl = boost::mpl;
using namespace msm::front;
// events
struct coin {};
struct push {};
// front-end: define the FSM structure
struct autodoor_ : public msm::front::state_machine_def<autodoor_>
{
//
struct Locked : public msm::front::state<>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& )
{
std::cout << "entering: Locked" << std::endl;
}
template <class Event,class FSM>
void on_exit(Event const&,FSM& )
{
std::cout << "leaving: Locked" << std::endl;
}
};
//
struct Unlocked : public msm::front::state<>
{
template <class Event,class FSM>
void on_entry(Event const&,FSM& )
{
std::cout << "entering: Unlocked" << std::endl;
}
template <class Event,class FSM>
void on_exit(Event const&,FSM& )
{
std::cout << "leaving: Unlocked" << std::endl;
}
};
// the initial state of the player SM. Must be defined
typedef Locked initial_state;
// transition actions
void locked_coin(coin const&)
{
std::cout << "locked::coin\n" << std::endl;
}
void locked_push(push const &)
{
std::cout << "Locked::push\n" << std::endl;
}
void unlocked_coin(coin const &)
{
std::cout << "Unlocked::coin\n" << std::endl;
}
void unlocked_push(push const &)
{
std::cout << "Unlocked::push\n" << std::endl;
}
// Transition table for player
struct transition_table : mpl::vector<
// Start Event Next Action Guard
// +---------+-------------+---------+---------------------+----------------------+
a_row < Locked , coin , Unlocked , &autodoor_::locked_coin >,
a_row < Locked , push , Locked , &autodoor_::locked_push >,
// +---------+-------------+---------+---------------------+----------------------+
a_row < Unlocked, coin , Unlocked , &autodoor_::unlocked_coin >,
a_row < Unlocked, push , Locked , &autodoor_::unlocked_push >
// +---------+-------------+---------+---------------------+----------------------+
> {};
};
// Pick a back-end
typedef msm::back::state_machine<autodoor_> autodoor;
//
// Testing utilities.
//
static char const* const state_names[] = { "Locked", "Unlocked"};
void pstate(autodoor const& d)
{
std::cout << " -> " << state_names[d.current_state()[0]] << std::endl;
}
void test()
{
autodoor d;
// needed to start the highest-level SM. This will call on_entry and mark the start of the SM
d.start();
d.process_event(push());
pstate(d);
d.process_event(coin());
pstate(d);
d.process_event(push());
pstate(d);
d.process_event(coin());
pstate(d);
}
int main()
{
test();
return 0;
}有限自动状态机
这篇博客介绍了一个使用Boost库实现的有限自动状态机(FSM)示例,展示了如何定义状态、事件、转换动作和转换表。示例中,FSM有两个状态:Locked和Unlocked,事件包括coin和push。通过处理这些事件,FSM可以在不同状态之间切换,并打印相应的状态变化信息。
5263

被折叠的 条评论
为什么被折叠?



