Skip to content

Instantly share code, notes, and snippets.

@eskil
Created December 16, 2013 22:53
Show Gist options
  • Save eskil/7996070 to your computer and use it in GitHub Desktop.
Save eskil/7996070 to your computer and use it in GitHub Desktop.
class simple;
typedef statemachines::traits<my_state_type, threads::single_threaded> my_traits;
class simple : public statemachines::statemachine<simple, my_traits> {
public:
class generic_event : public event_t {};
class one_event : public event_t {
public:
one_event (std::string msg) : m_message (msg) {}
std::string m_message;
};
class loop_event : public event_t {};
class failure_event : public event_t {};
simple () {
*this << graphviz_t ("test_graph")
<< begin_t (initial_state)
//------------------------+---------------+-------------+---------------------------+---------------------
// Event From-State To-State Action Description
<< edge_t<one_event> (initial_state, one_state, &simple::action, "we got a 1")
<< edge_t<failure_event> (initial_state, fail_state)
<< edge_t<loop_event> (initial_state, loop_1_state, "got a loop event")
<< edge_t<loop_event> (one_state, loop_2_state, &simple::loop_2_action, "got a loop event")
<< edge_t<loop_event> (loop_1_state, loop_2_state, &simple::loop_2_action)
<< edge_t<loop_event> (loop_2_state, loop_1_state, "do a loop")
<< edge_t<generic_event> (fail_state, end_state)
<< edge_t<generic_event> (one_state, end_state, &simple::end_action, "")
<< edge_t<generic_event> (loop_1_state, end_state, &simple::end_action, "generic")
<< edge_t<generic_event> (loop_2_state, end_state, &simple::end_action, "generic");
//------------------------+---------------+-------------+---------------------------+---------------------
}
void action (const one_event &foo) {
printf ("action for one_event : %s\n", foo.m_message.c_str ());
m_count ++;
}
void end_action (const generic_event &foo) {
printf ("reached the end of the line\n");
m_count ++;
}
void loop_2_action (const loop_event &foo) {
printf ("loop\n");
prepost_event (new loop_event);
m_count ++;
}
void run (const std::string &name) {
m_count = 0;
// exercise it a bit
post_event (new one_event ("hello world!"));
post_event (new loop_event);
post_event (new loop_event);
post_event (new generic_event);
while (handle_event ()) { }
assert (m_count == 4);
save_to_postscript (name);
}
void save_to_postscript (std::string name) {
// create ps file showing state machine
name.erase (0, 2);
std::ofstream dotfile;
dotfile.open ((name + ".dot").c_str ());
dotfile << toGraphViz ();
dotfile.close ();
std::string cmd ("dot -Tps -o ");
cmd += (name + ".ps " + name + ".dot ");
std::cout << cmd << std::endl;
system (cmd.c_str ());
}
private:
int m_count;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment