Dr. Dobb's is part of the Informa Tech Division of Informa PLC

This site is operated by a business or businesses owned by Informa PLC and all copyright resides with them. Informa PLC's registered office is 5 Howick Place, London SW1P 1WG. Registered in England and Wales. Number 8860726.


Channels ▼
RSS

Object-Oriented Finite-State Machines


February 1998/Object-Oriented Finite-State Machines/Listing 1

Listing 1: Client class FSM

//----------- FSM declaration ------------
#include "ABS_eventhandler.h"
#include "list.h"
typedef struct StructEvent
{
    // event identifier
    int     Id;            
    // event parameters
    void    *parameters;
} STRUCT_EVENT;
Makelista(STRUCT_EVENT);
class FSM    
{
 private :
    typedef struct
    {
        int  source_state;
        int  destination_state;
        int  event;
        int  index;
    } TransitionType;
    
    TransitionType* myptrArrayTrans; // a pointer to the
                                     // array of transitions
    int myMaxNumTransitions; // max transitions supported
    int myCurrentState;      // current state of the FSM
    // an event queue                                    
    
    STRUCT_EVENTlista myList;            
    
    
    ABSEventHandler* myptrHandler; // a pointer to the 
                                   // abstract server class
    void insertInQueue(int inEvent, void *inParameters );
    // Search using hash functions
    int hash(int inSourceState, int inEvent);
    int hash(int inEvent);
 public :
    // Constructor
        FSM(ABSEventHandler *inTrans, int inMaxNumTransitions, 
            int inInitialState );
    // Destructor
        ~FSM( void );
    void defineTransition(int inSourceState, int inDestinationState,
                          int inEvent, int inIndex);
    int control(int inEvent, void *inParameters = NULL );
    void  generateEvent(int inEvent, void *inParameters = NULL );
};    
//----------- FSM definition ------------
#include <memory.h>
#include <stdlib.h>
#include "FSM.h"
FSM::FSM(ABSEventHandler *inTrans, int inMaxNumTransitions, 
         int inInitialState)
{
 myptrHandler = inTrans;
 // Initialize the maximal number of transitions
 myMaxNumTransitions = inMaxNumTransitions;
 // Initialize the current state
 myCurrentState = inInitialState;
 // Initialize the array of transitions
 myptrArrayTrans = 0;
 myptrArrayTrans = new TransitionType[myMaxNumTransitions];
 memset(myptrArrayTrans, -1,
        myMaxNumTransitions * sizeof(TransitionType));
}
FSM::~FSM()
{
 if ( myptrArrayTrans )
    delete []myptrArrayTrans;
}
void FSM::insertInQueue(int inEvent, void *inParametros)
// not shown
int FSM::hash(int inSourceState, int inEvent)
{
 int  i = 0;
 int  where = ((inEvent << 8) + inSourceState) % myMaxNumTransitions;

 // Look for the first available position
 while((myptrArrayTrans[(where + i)%myMaxNumTransitions].index != -1)
         && (i < myMaxNumTransitions))
    i++;
 // Return negative value if the table is full
 if ( i >= myMaxNumTransitions )
    return -1;
 else  // Return free position?s index
    return ((where + i) % myMaxNumTransitions);
}
int FSM::hash( int inEvent )
{
 int i = 0;
 int where = ((inEvent << 8) + myCurrentState) % myMaxNumTransitions;
// rest the same as above
}
int FSM::defineTransition(int inSourceState, int inDestinationState,
                          int inEvent, int inIndex)
{
 int index;
 // Search free position in the table of transitions
 index = hash(inSourceState, inEvent);
 if ( index != -1 )
 {
    myptrArrayTrans[index].source_state = inSourceState;
    myptrArrayTrans[index].destination_state = inDestinationState;
    myptrArrayTrans[index].event = inEvent;
    myptrArrayTrans[index].index = inIndex;
 }
 return index;
}
int FSM::control( int inEvent, void *inParametros )
{
 int          result     = FALSE;
 int          trans_num;
 StructEvent* anEvent    = NULL;
 // Insert the received event in the queue
 insertInQueue(inEvent, inParametros);
 anEvent = myList.first();
 while ( anEvent )
 {
    // check if it is valid transition
    if ((trans_num = hash(anEvent->Id)) >= 0)
    {
       if (myptrArrayTrans[trans_num].index == -1)
       {
           // Missing transition - generate an internal error event
           generateEvent(INTERNAL_ERROR);
       }
       else
       {
           // Execute an event handler
           result = (myptrHandler->*myptrHandler->
               functions[myptrArrayTrans[trans_num].index])
                   (anEvent->parameters);
        // Change the FSM's state
        myCurrentState =
            myptrArrayTrans[trans_num].destination_state;
       }
    }
    // Missing transition - generate an internal error event
    else
    {
        generateEvent(INTERNAL_ERROR);
    }
    // Remove the processed event
    myList.remove(anEvent);
    // pull the next event 
    // from the queue
    anEvent = myList.next();
 } 
 return result;
}
void FSM::generateEvent(int inEvent, void *inParametros )
{
 insertInQueue(inEvent, inParametros);
}
//End of File

Related Reading


More Insights






Currently we allow the following HTML tags in comments:

Single tags

These tags can be used alone and don't need an ending tag.

<br> Defines a single line break

<hr> Defines a horizontal line

Matching tags

These require an ending tag - e.g. <i>italic text</i>

<a> Defines an anchor

<b> Defines bold text

<big> Defines big text

<blockquote> Defines a long quotation

<caption> Defines a table caption

<cite> Defines a citation

<code> Defines computer code text

<em> Defines emphasized text

<fieldset> Defines a border around elements in a form

<h1> This is heading 1

<h2> This is heading 2

<h3> This is heading 3

<h4> This is heading 4

<h5> This is heading 5

<h6> This is heading 6

<i> Defines italic text

<p> Defines a paragraph

<pre> Defines preformatted text

<q> Defines a short quotation

<samp> Defines sample computer code text

<small> Defines small text

<span> Defines a section in a document

<s> Defines strikethrough text

<strike> Defines strikethrough text

<strong> Defines strong text

<sub> Defines subscripted text

<sup> Defines superscripted text

<u> Defines underlined text

Dr. Dobb's encourages readers to engage in spirited, healthy debate, including taking us to task. However, Dr. Dobb's moderates all comments posted to our site, and reserves the right to modify or remove any content that it determines to be derogatory, offensive, inflammatory, vulgar, irrelevant/off-topic, racist or obvious marketing or spam. Dr. Dobb's further reserves the right to disable the profile of any commenter participating in said activities.

 
Disqus Tips To upload an avatar photo, first complete your Disqus profile. | View the list of supported HTML tags you can use to style comments. | Please read our commenting policy.