1 /********************************************** 2 状态机示例 3 功能:从屏幕输入1,则输出yes,输入其他值输出no 4 ***********************************************/ 5 #include <stdio.h> 6 #include <string.h> 7 8 /* 在各状态之间传递的消息*/ 9 typedef struct stateInfo 10 { 11 int message; 12 int nextStateID; 13 char result[12]; 14 }StateT; 15 16 /* 每一个状态会执行一个动作,再判断该转到哪个状态去*/ 17 typedef void (*sAction) (StateT *pStateInfo); 18 typedef int (*sTrans) (StateT *pStateInfo); 19 typedef struct smt 20 { 21 sAction action; 22 sTrans trans; 23 }MyStateMachine_T; 24 25 /*以下是每个状态点的具体实现,State1~4*/ 26 void State1_action(StateT *pStateInfo) 27 { 28 int msg = 0; 29 scanf("%d",&msg); 30 pStateInfo->message = msg; 31 return; 32 } 33 int State1_trans(StateT *pStateInfo) 34 { 35 if(pStateInfo->message == 1) 36 { 37 pStateInfo->nextStateID = 1; 38 } 39 else 40 { 41 pStateInfo->nextStateID = 2; 42 } 43 return 1; 44 } 45 void State2_action(StateT *pStateInfo) 46 { 47 strncpy(pStateInfo->result ,"yes",3); 48 return; 49 } 50 int State2_trans(StateT *pStateInfo) 51 { 52 pStateInfo->nextStateID = 3; 53 return 1; 54 } 55 void State3_action(StateT *pStateInfo) 56 { 57 strncpy(pStateInfo->result ,"no",2); 58 return; 59 } 60 int State3_trans(StateT* pStateInfo) 61 { 62 pStateInfo->nextStateID = 3; 63 return 1; 64 } 65 void State4_action(StateT *pStateInfo) 66 { 67 printf("result: %s \r\n",pStateInfo->result); 68 return; 69 } 70 int State4_trans(StateT* pStateInfo) 71 { 72 pStateInfo->nextStateID = 0; 73 return 0; 74 } 75 76 /* 这个示例中,状态机由四个状态构成*/ 77 MyStateMachine_T myfsm[4]= 78 { 79 {State1_action,State1_trans}, 80 {State2_action,State2_trans}, 81 {State3_action,State3_trans}, 82 {State4_action,State4_trans} 83 }; 84 int main(void) 85 { 86 StateT stateinfo; 87 memset(&stateinfo,0,sizeof(StateT)); 88 89 /*进入初始状态State1,通过状态机是放在一个任务里的,常驻内存,随时接收消息 90 这里写得简单,只是从屏幕上读入值。 91 */ 92 MyStateMachine_T *pfsm = &myfsm[0]; 93 pfsm->action(&stateinfo); 94 while(1 == pfsm->trans(&stateinfo)) 95 { 96 pfsm = &myfsm[stateinfo.nextStateID]; 97 pfsm->action(&stateinfo); 98 } 99 return 0; 100 }
运行结果:
fanyuchao@dell-desktop:~/CProjectSpace/FSM$ ./fsm
1
result: yes
fanyuchao@dell-desktop:~/CProjectSpace/FSM$ ./fsm
2
result: no