当前状态 输入 下一个状态 动作 s1 c1 s2 a1 s2 c2 s3 a2 s3 c1 s2 a3 s2 c2 s3 a2 s3 c1 s2 a3 s2 c1 s_trap a_trap s_trap c1 s_trap a_trap

typedef int State;
typedef int Condition;

#define STATES 3 + 1
#define STATE_1 0
#define STATE_2 1
#define STATE_3 2
#define STATE_TRAP 3

#define CONDITIONS 2
#define CONDITION_1 0
#define CONDITION_2 1


typedef void (*ActionType)(State state, Condition condition);

typedef struct
{
State next;
ActionType action;
} Trasition, * pTrasition;


// (s1, c1, s2, a1)
Trasition t1 = {
STATE_2,
action_1
};

// (s2, c2, s3, a2)
Trasition t2 = {
STATE_3,
action_2
};

// (s3, c1, s2, a3)
Trasition t3 = {
STATE_2,
action_3
};

// (s, c, trap, a1)
Trasition tt = {
STATE_TRAP,
action_trap
};


void action_1(State state, Condition condition)
{
printf("Action 1 triggered.\n");
}

最后定义跳转表：
pTrasition transition_table[STATES][CONDITIONS] = {
/*		c1,  c2*/
/* s1 */&t1, &tt,
/* s2 */&tt, &t2,
/* s3 */&t3, &tt,
/* st */&tt, &tt,
};


typedef struct
{
State current;
} StateMachine, * pStateMachine;

State step(pStateMachine machine, Condition condition)
{
pTrasition t = transition_table[machine->current][condition];
(*(t->action))(machine->current, condition);
machine->current = t->next;
return machine->current;
}


#define E_OK		0
#define E_NO_DATA	1
#define E_OVERFLOW	2

typedef struct
{
Condition queue[QMAX];
int tail;
bool overflow;
} ConditionQueue, * pConditionQueue;

int push(ConditionQueue * queue, Condition c)
{
unsigned int flags;
Irq_Save(flags);
if ((queue->head == queue->tail + 1) || ((queue->head == 0) && (queue->tail == 0)))
{
queue->overflow = true;
Irq_Restore(flags);
return E_OVERFLOW;
}
else
{
queue->queue[queue->tail] = c;
queue->tail = (queue->tail + 1) % QMAX;
Irq_Restore(flags);
}
return E_OK;
}

int poll(ConditionQueue * queue, Condition * c)
{
unsigned int flags;
Irq_Save(flags);
{
Irq_Restore(flags);
return E_NO_DATA;
}
else
{
queue->overflow = false;
Irq_Restore(flags);
}
return E_OK;
}

typedef struct
{
State current;
bool inTransaction;
ConditionQueue queue;
} StateMachine, * pStateMachine;

static State __step(pStateMachine machine, Condition condition)
{
State current = machine -> current;
pTrasition t = transition_table[current][condition];
(*(t->action))(current, condition);
current = t->next;
machine->current = current;
return current;
}

State step(pStateMachine machine, Condition condition)
{
Condition next_condition;
int status;
State current;
if (machine->inTransaction)
{
push(&(machine->queue), condition);
return STATE_INTRANSACTION;
}
else
{
machine->inTransaction = true;
current = __step(machine, condition);
status = poll(&(machine->queue), &next_condition);
while(status == E_OK)
{
__step(machine, next_condition);
status = poll(&(machine->queue), &next_condition);
}
machine->inTransaction = false;
return current;
}
}

void initialize(pStateMachine machine, State s)
{
machine->current = s;
machine->inTransaction = false;