tags:

views:

506

answers:

7

Hi Folks,

I want to write an FSM which starts with an idle state and moves from one state to another based on some event. I am not familiar with coding of FSM and google didn't help. Appreciate if someone could post the C data structure that could be used for the same.

Thanks, syuga2012

A: 
Adam Rosenfield
A: 

You can basically use "if" conditional and a variable to store the current state of FSM.

For example (just a concept):

int state = 0;
while((ch = getch()) != 'q'){
    if(state == 0)
        if(ch == '0')
            state = 1;
        else if(ch == '1')
            state = 0;
    else if(state == 1)
        if(ch == '0')
            state = 2;
        else if(ch == '1')
            state = 0;
    else if(state == 2)
    {
        printf("detected two 0s\n");
        break;
    }
}

For more sophisticated implementation, you may consider store state transition in two dimension array:

int t[][] = {{1,0},{2,0},{2,2}};
int state = 0;

while((ch = getch()) != 'q'){
    state = t[state][ch - '0'];
    if(state == 2){
        ...
    }
}
m3rLinEz
A: 

if by FSM you mean finite state machine, and you like it simple, use enums to name your states and switch betweem them.

Otherwise use functors. you can look the fancy definition up in the stl or boost docs.

They are more or less objects, that have a method e.g. called run(), that executes everything that should be done in that state, with the advantage that each state has it's own scope.

AndreasT
+1  A: 

We've implemented finite state machine for Telcos in the past and always used an array of structures, pre-populated like:

/* States */
#define ST_ANY    0
#define ST_START  1
: : : : :

/* Events */
#define EV_INIT   0
#define EV_ERROR  1
: : : : :

/* Rule functions */
int initialize(void) {
    /* Initialize FSM here */
    return ST_INIT_DONE
}
: : : : :

/* Structures for transition rules */
typedef struct {
    int state;
    int event;
    (int)(*fn)();
} rule;
rule ruleset[] = {
    {ST_START, EV_INIT, initialize},
    : : : : :
    {ST_ANY, EV_ERROR, error},
    {ST_ANY, EV_ANY, fatal_fsm_error}
};

I may have the function pointer fn declared wrong since this is from memory. Basically the state machine searched the array for a relevant state and event and called the function which did what had to be done then returned the new state.

The specific states were put first and the ST_ANY entries last since priority of the rules depended on their position in the array. The first rule that was found was the one used.

In addition, I remember we had an array of indexes to the first rule for each state to speed up the searches (all rules with the same starting state were grouped).

Also keep in mind that this was pure C - there may well be a better way to do it with C++.

paxdiablo
A: 

A few guys from AT&T, now at Google, wrote one of the best FSM libraries available for general use. Check it out here, it's called OpenFST.

It's fast, efficient, and they created a very clear set of operations you can perform on the FSMs to do things like minimize them or determinize them to make them even more useful for real world problems.

Chris Harris
+1  A: 

A finite state machine consists of a finite number discrete of states (I know pedantic, but still), which can generally be represented as integer values. In c or c++ using an enumeration is very common.

The machine responds to a finite number of inputs which can often be represented with another integer valued variable. In more complicated cases you can use a structure to represent the input state.

Each combination of internal state and external input will cause the machine to:

  1. possibly transition to another state
  2. possibly generate some output

A simple case in c might look like this

enum state_val {
   IDLE_STATE,
   SOME_STATE,
   ...
   STOP_STATE
}
//...    
  state_val state = IDLE_STATE
  while (state != STOP_STATE){
    int input = GetInput();
    switch (state) {
    case IDLE_STATE:
      switch (input) {
        case 0:
        case 3: // note the fall-though here to handle multiple states
          write(input); // no change of state
          break;
        case 1: 
          state = SOME_STATE;
          break
        case 2:
          // ...
      };
      break;
    case SOME_STATE:
      switch (input) {
        case 7:
          // ...
      };
      break;
    //...
    };
  };
  // handle final output, clean up, whatever

though this is hard to read and more easily split into multiple function by something like:

  while (state != STOP_STATE){
     int input = GetInput();
     switch (state) {
     case IDLE_STATE:
       state = DoIdleState(input);
       break;
     // ..
     };
  };

with the complexities of each state held in it's own function.

As m3rLinEz says, you can hold transitions in an array for quick indexing. You can also hold function pointer in an array to efficiently handle the action phase. This is especially useful for automatic generation of large and complex state machines.

dmckee
+1  A: 

The answers here seem really complex (but accurate, nonetheless.) So here are my thoughts.

First, I like dmckee's (operational) definition of an FSM and how they apply to programming.

A finite state machine consists of a finite number discrete of states (I know pedantic, but still), which can generally be represented as integer values. In c or c++ using an enumeration is very common.

The machine responds to a finite number of inputs which can often be represented with another integer valued variable. In more complicated cases you can use a structure to represent the input state.

Each combination of internal state and external input will cause the machine to:

  1. possibly transition to another state
  2. possibly generate some output

So you have a program. It has states, and there is a finite number of them. ("the light bulb is bright" or "the light bulb is dim" or "the light bulb is off." 3 states. finite.) Your program can only be in one state at a time.

So, say you want your program to change states. Usually, you'll want something to happen to trigger a state change. In this example, how about we take user input to determine the state - say, a key press.

You might want logic like this. When the user presses a key:

  1. If the bulb is "off" then make the bulb "dim".
  2. If the bulb is "dim", make the bulb "bright".
  3. If the bulb is "bright", make the bulb "off".

Obviously, instead of "changing a bulb", you might be "changing the text color" or whatever it is you program needs to do. Before you start, you'll want to define your states.

So looking at some pseudoish C code:

/* We have 3 states. We can use constants to represent those states */
#define BULB_OFF 0
#define BULB_DIM 1
#define BULB_BRIGHT 2

/* And now we set the default state */
int currentState = BULB_OFF;

/* now we want to wait for the user's input. While we're waiting, we are "idle" */
while(1) {
   waitForUserKeystroke(); /* Waiting for something to happen... */

   /* Okay, the user has pressed a key. Now for our state machine */

   switch(currentState) {
      case BULB_OFF:
         currentState = BULB_DIM;
         break;
      case BULB_DIM:
         currentState = BULB_BRIGHT;
         doCoolBulbStuff();
         break;
      case BULB_BRIGHT:
         currentState = BULB_OFF;
         break;
   }
}

And, voila. A simple program which changes the state.

This code executes only a small part of the switch statement - depending on the current state. Then it updates that state. That's how FSMs work.

Now here are some things you can do:

  1. Obviously, this program just changes the currentState variable. You'll want your code to do something more interesting on a state change. The doCoolBulbStuff() function might, i dunno, actually put a picture of a lightbulb on a screen. Or something.

  2. This code only looks for a keypress. But your FSM (and thus your switch statement) can choose state based on what the user inputted (eg, "O" means "go to off" rather than just going to whatever is next in the sequence.)

Part of your question asked for a data structure.

One person suggested using an enum to keep track of states. This is a good alternative to the #defines that I used in my example. People have also been suggesting arrays - and these arrays keep track of the transitions between states. This is also a fine structure to use.

Given the above, well, you could use any sort of structure (something tree-like, an array, anything) to keep track of the individual states and define what to do in each state (hence some of the suggestions to use "function pointers" - have a state map to a function pointer which indicates what to do at that state.)

Hope that helps!

rascher