2018年1月29日 星期一

[C] Finite State machine (FSM)


#include <stdio.h>

typedef struct {
    int st;
    int ev;
    int (*fn)(void);
} tTransition;

enum states { ST_ANY, ST_INIT, ST_ERROR, ST_TERM } current_state;
enum events { EV_ANY, EV_KEYPRESS, EV_MOUSEMOVE } new_event;

static int GotKey (void) {}
static int FsmError (void) {}

tTransition trans[] = {
    { ST_INIT, EV_KEYPRESS, &GotKey},
    { ST_ANY, EV_ANY, &FsmError}
};
#define TRANS_COUNT (sizeof(trans)/sizeof(*trans))

/* Return the next event to process - how this works depends on your
application. */

enum events GetNextEvent (void)
{
    printf("start new event \n");
    return EV_ANY;
}

void main (void)
{
 int i = 0;

 current_state = ST_INIT;
 while (current_state != ST_TERM) {
  new_event = GetNextEvent();
  for (i = 0; i < TRANS_COUNT; i++) {
   if ((current_state == trans[i].st) || (ST_ANY == trans[i].st)) {
    if ((new_event == trans[i].ev) || (EV_ANY == trans[i].ev)) {
     current_state = (trans[i].fn)();
     break;
    }
   }
  }
 }
}

Ref:

0 意見:

張貼留言