enum message { play, stop, forward, backward, record, pause };
状态迁移表与状态迁移图完全等价。
1 struct transition fsm[transition_num] = {
2 /* current_state, message/event, next_state*/
3 {s_play, stop, s_stop},
4 {s_play, pause, s_pause},
5 {s_pause, pause, s_play},
6 {s_pause, stop, s_stop},
7 {s_stop, forward, s_forward},
8 {s_stop, play, s_play},
9 {s_stop, backward, s_backward},
10 {s_stop, record, s_record},
11 {s_forward, stop, s_stop},
12 {s_backward, stop, s_stop},
13 {s_record, stop, s_stop} };
1 enum state { s_stop=‘s‘, s_play=‘p‘, s_forward=‘f‘, s_backward=‘b‘, s_pause=‘_‘, s_record=‘r‘ };
2 enum message { play, stop, forward, backward, record, pause };
3
4 struct transition {
5 enum state current;
6 enum message m;
7 enum state next;
8 };
1 #define transition_num 11
1 struct state_action state_action_map[state_num] = {
2 {s_stop, do_stop},
3 {s_play, do_play},
4 {s_forward, do_forward},
5 {s_backward, do_backward},
6 {s_pause, do_pause},
7 {s_record, do_record}};
1 #define state_num 6
2 typedef void (*action_foo)() ;
3
4 enum state { s_stop=‘s‘, s_play=‘p‘, s_forward=‘f‘, s_backward=‘b‘, s_pause=‘_‘, s_record=‘r‘ };
5
6 /* action starts */
7 void do_stop() {printf ("I am in state stop and should doing something here.\n");}
8 void do_play() {printf ("I am in state play and should doing something here.\n");}
9 void do_forward() {printf ("I am in state forward and should doing something here.\n");}
10 void do_backward() {printf ("I am in state backward and should doing something here.\n");}
11 void do_pause() {printf ("I am in state pause and should doing something here.\n");}
12 void do_record() {printf ("I am in state record and should doing something here.\n");}
13
14 struct state_action {
15 enum state m_state;
16 action_foo foo;
17 };
1 void state_change(enum message m)
2 {
3 static state = s_stop;
4 enum state next;
5 int index = 0;
6
7 index = lookup_transition(state, m, fsm);
8 if(index!=ERR)
9 {
10 state = fsm[index].next;
11 lookup_action(state, state_action_map)();
12 }
13 return;
14 }
1 int const ERR = -1;
2 int lookup_transition (enum state s, enum message m, struct transition * t)
3 {
4 int ret=ERR;
5 int i;
6 for(i=0;i<transition_num;++i)
7 {
8 if(t[i].current == s && t[i].m == m)
9 {
10 ret = i;
11 }
12 }
13 return ret;
14 }
15
16 action_foo ACTION_NOT_FOUND = NULL;
17 action_foo lookup_action(enum state s, struct state_action* a)
18 {
19 action_foo ret = ACTION_NOT_FOUND;
20 int i=0;
21 for (i=0;i<state_num;++i)
22 {
23 if(s == a[i].m_state)
24 {
25 ret = a[i].foo;
26 }
27 }
28 return ret;
29 }
这一篇和上一篇的代码在这里[http://download.csdn.net/detail/younggift/7569627]。
geek青年的状态机,查表,纯C语言实现,布布扣,bubuko.com
原文:http://blog.csdn.net/younggift/article/details/35848677