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
|
#include "fsm.h" static void fsm_state_transfer(fsm_ptr p_fsm, const char* state) { p_fsm->current_state = state; }
void fsm_event_handle(fsm_ptr p_fsm, const char* event, void *param) { fsm_table table; void (*action_func)(void *) = NULL; const char* next_state; const char* current_state = p_fsm->current_state; uint8_t flag = 0;
for (uint8_t i = 0; i < p_fsm->tables.listsize_; i++) { darr_get(&p_fsm->tables, i, &table); if (event == table.event && current_state == table.current_state) { flag = 1; action_func = table.action_func; next_state = table.next_state; break; } } if (flag) { if (action_func != NULL) action_func(param); fsm_state_transfer(p_fsm, next_state); } else { } }
void fsm_init(fsm_ptr p_fsm) { p_fsm->states = darr_initiate(sizeof(const char*)); p_fsm->events = darr_initiate(sizeof(const char*)); p_fsm->tables = darr_initiate(sizeof(fsm_table)); }
void fsm_state_register(fsm_ptr p_fsm, const char* state_name) { uint8_t flag = 1; for(int i = 0; i < p_fsm->states.listsize_; i++) { char* existed_state = NULL; darr_get(&p_fsm->states, i, &existed_state); if (state_name == existed_state) { flag = 0; break; } } if(flag) { darr_push(&p_fsm->states, &state_name); if(p_fsm->states.listsize_ == 1) p_fsm->current_state = state_name; } }
void fsm_event_register(fsm_ptr p_fsm, const char* event_name) { uint8_t flag = 1; for(uint8_t i = 0; i < p_fsm->events.listsize_; i++) { char* existed_event = NULL; darr_get(&p_fsm->events, i, &existed_event); if (event_name == existed_event) { flag = 0; break; } } if(flag) darr_push(&p_fsm->events, &event_name); }
void fsm_table_register(fsm_ptr p_fsm, fsm_table_ptr p_table) { uint8_t flag = 1; for(uint8_t i = 0; i < p_fsm->tables.listsize_; i++) { fsm_table table; darr_get(&p_fsm->tables, i, &table); if (p_table->current_state == table.current_state && p_table->next_state == table.next_state) { flag = 0; break; } } if(flag) { darr_push(&p_fsm->tables, p_table); fsm_state_register(p_fsm, p_table->current_state); fsm_state_register(p_fsm, p_table->next_state); fsm_event_register(p_fsm, p_table->event); } }
void fsm_destroy(fsm_ptr p_fsm) { darr_clear(&p_fsm->states); darr_clear(&p_fsm->events); darr_clear(&p_fsm->tables); p_fsm = NULL; }
|