1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
| #include <stdio.h> #include <unistd.h>
enum { GET_UP, GO_TO_SCHOOL, HAVE_LUNCH, DO_HOMEWORK, SLEEP, };
enum { EVENT1 = 1, EVENT2, EVENT3, };
typedef struct FsmTable_s { int event; int CurState; void (*eventActFun)(); int NextState; }FsmTable_t;
typedef struct FSM_s { FsmTable_t* FsmTable; int curState; }FSM_t;
int g_max_num;
void GetUp() { printf("xiao ming gets up!\n"); } void Go2School() { printf("xiao ming goes to school!\n"); } void HaveLunch() { printf("xiao ming has lunch!\n"); } void DoHomework() { printf("xiao ming does homework!\n"); } void Go2Bed() { printf("xiao ming goes to bed!\n"); }
void FSM_Regist(FSM_t* pFsm, FsmTable_t* pTable) { pFsm->FsmTable = pTable; }
void FSM_StateTransfer(FSM_t* pFsm, int state) { pFsm->curState = state; }
void FSM_EventHandle(FSM_t* pFsm, int event) { FsmTable_t* pActTable = pFsm->FsmTable; void (*eventActFun)() = NULL; int NextState; int CurState = pFsm->curState; int flag = 0; int i;
for (i = 0; i<g_max_num; i++) { if (event == pActTable[i].event && CurState == pActTable[i].CurState) { flag = 1; eventActFun = pActTable[i].eventActFun; NextState = pActTable[i].NextState; break; } }
if (flag) { if (eventActFun) { eventActFun(); } FSM_StateTransfer(pFsm, NextState); } else { } }
FsmTable_t XiaoMingTable[] = { { EVENT1, SLEEP, GetUp, GET_UP }, { EVENT2, GET_UP, Go2School, GO_TO_SCHOOL }, { EVENT3, GO_TO_SCHOOL, HaveLunch, HAVE_LUNCH }, { EVENT1, HAVE_LUNCH, DoHomework, DO_HOMEWORK }, { EVENT2, DO_HOMEWORK, Go2Bed, SLEEP }, };
void InitFsm(FSM_t* pFsm) { g_max_num = sizeof(XiaoMingTable) / sizeof(FsmTable_t); pFsm->curState = SLEEP; FSM_Regist(pFsm, XiaoMingTable); }
void test(int *event) { if (*event == 3) { *event = 1; } else { (*event)++; }
}
int main() { FSM_t fsm; InitFsm(&fsm); int event = EVENT1; while (1) { printf("event %d is coming...\n", event); FSM_EventHandle(&fsm, event); printf("fsm current state %d\n", fsm.curState); test(&event); sleep(1); }
return 0; }
|