#include <stdio.h>
void char_put(int); // Our putchar() function
void (*pFunc)(int); // Function pointer
enum states { before = 0, inside = 1, after = 2 };
enum events {event_space = 0, event_cr = 1, event_char = 2};
class StateMachine
{
private:
enum states state_curr; // Current state
struct branch
{
int event_type:3;
enum states state_new:2;
int do_func:1;
};
static struct branch transition_table[3][3]; // Transition map
public:
StateMachine(states state_init) : state_curr(before) // Constructor with starting state
{
state_curr = state_init;
}
void process_event(int c)
{
printf("\nCurrent State %i \n", state_curr);
int idx = (c == ' ') ? event_space : (c == '\n') ? event_cr : event_char;
printf("Event Recieved: %i \n", idx);
struct branch *b = &transition_table[state_curr][idx];
state_curr = b->state_new;
printf("Next State: %i \n", state_curr);
if(b->do_func)
{
// pFunc = b->do_func; // ERROR: Invalid conversion from ‘int’ to ‘void (*)(int)
printf("pFunc Address: %0X \n", pFunc);
// pFunc(c); // Should work if I can assign the func address above
char_put(c);
}
}
};
struct StateMachine::branch StateMachine::transition_table[3][3] =
{
/* Current state
Recieved event, New state, pFunc to exec */
{ // State: before
{event_space, before, 0},
{event_cr, before, 1},
{event_char, inside, 1}
// {event_char, inside, &char_put} // ERROR: Invalid conversion from ‘void (*)(int)’ to ‘int’
},
{ // State: inside
{event_space, after, 0},
{event_cr, before, 1},
{event_char, inside, 1}
},
{ // State: after
{event_space, after, 0},
{event_cr, before, 1},
{event_char, after, 0}
}
};
int main(void)
{
printf("\n Welcome To The FSM Test");
printf("\n To exit the program press 'Esc'");
printf("\n\n");
int c;
StateMachine FSM(before); // Create & initlize state machine
printf("Type a message and I will discover the first word! \n Input: ");
while((c = getchar()) != '\33') // Read input untill ESC is recieved
{
FSM.process_event(c);
}
return 0;
}
void char_put(int c)
{
printf("FSM Says: %c \n", c);
}