Share

Hierarchical State Machine

In this article, we will be highlighting the advantages of hierarchical state machine design over conventional state machine design.

In conventional state machine design, all states are considered at the same level. The design does not capture the commonality that exists among states. In real life, many states handle most  messages in similar fashion and differ only in handling of few key messages. Even when the actual handling differs, there is still some commonality. Hierarchical state machine design captures the commonality by organizing the states as a hierarchy. The states at the higher level in hierarchy perform the common message handling, while the lower level states inherit the commonality from higher level ones and perform the state specific functions. The table given below shows the mapping between conventional states and their hierarchical counterparts for a typical call state machine.

Conventional States Hierarchical States
Awaiting First Digit Setup.CollectingDigits.AwaitingFirstDigit
Collecting Digits Setup.CollectingDigits.AwaitingSubsequent Digits
Routing Call Setup.RoutingCall
Switching Path Setup.SwitchingPath
Conversation Conversation
Awaiting Onhook Releasing.AwaitingOnhook
Releasing Path Releasing.ReleasingPath

A conventional state machine is designed as a two dimensional array with one dimension as the state and the other dimension specifying the message to be handled. The state machine determines the message handler to be called by indexing with the current state and the received message. In real life scenario, a task usually has a number of states along with many different types of input messages. This leads to a message handler code explosion. Also, a huge two dimensional array needs to be maintained. Hierarchical state machine design avoids this problem by recognizing that most states differ in the handling of only a few messages. When a new hierarchical state is defined, only the state specific handlers need to be specified.

Conventional State Machine Example

The figure below describes the state transition diagram for an active standby pair. The design here assumes that the active and standby are being managed by an external entity.

Conventional state transition diagram

The different states for the state machine are Active, Standby, Suspect and Failed. The input messages to be handled are Switchover, Fault Trigger, Diagnostics Passed, Diagnostics Failed and Operator Inservice. Thus the handler two dimensional array is 4 x 5 i.e. 20 handlers need to be managed.

The code below shows the handlers that need to be defined. A dummy "do nothing" handler should be specified for all other entries of the two dimensional state table. This simple example clearly illustrates the problem with conventional state design. There is a lot of code repetition between handlers. This creates a maintenance headache for state machine designers. We will see in the following section that hierarchical state machine design exploits these very similarities to implement a more elegant state structure.

Conventional State Machine Implementation

/* == Active State Handlers == */
void ActiveStateFaultTriggerHandler(Msg *pMsg)
 {
    PerformSwitchover();            // Perform Switchover, as active failed
    NextState = SUSPECT;            // Run diagnostics to confirm fault
    SendDiagnosticsRequest();
    RaiseAlarm(LOSS_OF_REDUNDANCY); // Report loss of redundancy to operator
 }
 
void ActiveStateSwitchoverHandler(Msg *pMsg)
{
  PerformSwitchover();              // Perform Switchover on operator command
  CheckMateStatus();                // Check if switchover completed
  SendSwitchoverResponse();         // Inform operator about switchover
  NextState = STANDBY;              // Transition to standby
}

/* == Standby State Handlers == */
void StandbyStateFaultTriggerHandler(Msg *pMsg)
{
  NextState = SUSPECT;              // Run diagnostics to confirm fault
  SendDiagnosticsRequest();
  RaiseAlarm(LOSS_OF_REDUNDANCY);   // Report loss of redundancy to operator
}

void StandbyStateSwitchoverHandler(Msg *pMsg)
{
  PerformSwitchover();              // Perform switchover on operator command
  CheckMateStatus();                // Check if switchover completed
  SendSwitchoverResponse();         // Inform operator about switchover
  NextState = ACTIVE;               // Transition to active
}

/* == Suspect State Handlers == */
void SuspectStateDiagnosticsFailedHandler(Msg *pMsg)
{
   SendDiagnosticsFailureReport();   // Inform operator about diagnostics
   NextState = FAILED;               // Move to the failed state
}

void SuspectStateDiagnosticsPassedHandler(Msg *pMsg)
{
   SendDiagnosticsPassReport();      // Inform operator about diagnostics
   ClearAlarm(LOSS_OF_REDUNDANCY);   // Clear loss of redundancy alarm
   NextState = STANDBY;              // Move to standby state
}

void SuspectStateOperatorInservice(Msg *pMsg)
{
   // Operator has replaced the card, so abort the current diagnostics
   // and restart new diagnostics on the replaced card.
   AbortDiagostics();   
   SendDiagnosticsRequest();         // Run diagnostics on replaced card
   SendOperatorInserviceResponse();  // Inform operator about diagnostics start
}
/* == Failed State Handlers == */
void FailedStateOperatorInservice(Msg *pMsg)
{
   SendDiagnosticsRequest();         // Run diagnostics on replaced card
   SendOperatorInserviceResponse();  // Inform operator about diagnostics start
   NextState = SUSPECT;              // Move to suspect state for diagnostics
}

Hierarchical State Machine Example

The following state transition diagram recasts the state machine by introducing two levels in the hierarchy. Inservice and Out_Of_Service are the high level states that capture the common message handling. Active and Standby states are low level states inheriting from Inservice state. Suspect and Failed are low level states inheriting from Out_Of_Service state.

Hierarchical state transition diagram

The following diagram clearly illustrates the state hierarchy. Even the Inservice and Out_Of_Service, high level states inherit from the Unit_State that is at the highest level.

State hierarchy for Unit

Hierarchical State Machine Source Code

The C++ implementation details of the hierarchical state machine are given below. It is apparent that all the commonality has moved to the high level states viz. Inservice and Out_Of_Service. Also, contrast this with the conventional state machine implementation.

The code below contains hyperlinks to more detailed information about the classes, methods and variables in this information.

Header File

The header file below declares the Unit state machine using the Hierarchical_State_Machine  class. Important points to note are:

  • The state classes are nested private classes within the state machine class. Thus they are not visible to other classes.
  • The state machine declares all states to be friend classes. This does not break the encapsulation as only a private class is being declared as a friend.
  • The base class (Unit_State) provides a "do nothing" implementation for all handlers. Thus an inheriting state has to provide an implementation only for that methods it supports.
  • State objects are declared static. Thus multiple instances of the state machine will share the same state objects. Due to this, the Hierarchical_State_Machine  class has a small memory footprint.
  • Only the main message handler, On_Message,  is declared public. All helper functions are private.
  • A pointer to the current state is maintained in p_Current_State variable. This variable gets initialized using the Next_State method.

Hierarchical_State_Machine.h

class Message;

class Hierarchical_State_Machine
{

    class Unit_State
    {
    public:

        virtual void On_Switchover(Hierarchical_State_Machine &u, 
                                     const Message *p_Message)  {} 

        virtual void On_Fault_Trigger(Hierarchical_State_Machine &u, 
                                        const Message *p_Message) {}  

        virtual void On_Diagnostics_Failed(Hierarchical_State_Machine &u, 
                                             const Message *p_Message) {}

        virtual void On_Diagnostics_Passed(Hierarchical_State_Machine &u, 
                                             const Message *p_Message) {}

        virtual void On_Operator_Inservice(Hierarchical_State_Machine &u, 
                                             const Message *p_Message) {}      
    };
    friend Unit_State;   



    class Inservice : public Unit_State
    {
    public:
        void On_Switchover(Hierarchical_State_Machine &u, 
                           const Message *p_Message);   
        void On_Fault_Trigger(Hierarchical_State_Machine &u, 
                              const Message *p_Message);
    };
    friend Inservice;   


    class Active : public Inservice
    {
    public:
        void On_Switchover(Hierarchical_State_Machine &u, 
                           const Message *p_Message);   
        void On_Fault_Trigger(Hierarchical_State_Machine &u, 
                              const Message *p_Message);
    };
    friend Active;    


    class Standby : public Inservice
    {
    public:
        void On_Switchover(Hierarchical_State_Machine &u, 
                           const Message *p_Message);   
    }; 
    friend Standby;   


    class Out_Of_Service : public Unit_State
    {
    public:
        void On_Operator_Inservice(Hierarchical_State_Machine &u, 
                                   const Message *p_Message);
    };
    friend Out_Of_Service;    

    class Suspect : public Out_Of_Service
    {
    public:
        void On_Diagnostics_Failed(Hierarchical_State_Machine &u, 
                                   const Message *p_Message);
        void On_Diagnostics_Passed(Hierarchical_State_Machine &u, 
                                   const Message *p_Message);
        void On_Operator_Inservice(Hierarchical_State_Machine &u, 
                                   const Message *p_Message);
    };
    friend Suspect;    

    class Failed : public Out_Of_Service
    {
    public:
        // No Need to Override any other method
    };
    friend Failed;    

private:
    static Active Active_State;   
    static Standby Standby_State; 
    static Suspect Suspect_State; 
    static Failed Failed_State;   

    void Next_State(Unit_State &r_State);
    

    // Common Methods invoked from several states
    // (See article on FSM Inheritance for details)
    virtual void Send_Diagnostics_Request();
    virtual void Raise_Alarm(int reason);
    virtual void Clear_Alarm(int reason);
    virtual void Perform_Switchover();
    // . . .
    virtual void Send_Switchover_Response();
    virtual void Send_Operator_Inservice_Response();
    virtual void Send_Diagnostics_Failure_Report();
    virtual void Send_Diagnostics_Pass_Report();
    virtual void Abort_Diagnostics();
    virtual void Check_Mate_Status();
    Unit_State *p_Current_State;   

public:
    void On_Message(const Message *p_Message);
};


void Hierarchical_State_Machine::Next_State(Unit_State &r_State)
{
    p_Current_State = &r_State;
}

Source File

Important things to note about the source file:

  • On_Message, the main message handler invokes the appropriate handler based on the type of the message. The message is passed to the current state object.
  • The Out_Of_Service and Inservice base states handle most of the message processing. In some cases, the inheriting states perform some additonal action and call the handler for the base state for the common part of the handling.

Hierarchical_State_Machine.cpp

#include "Hierarchical_State_Machine.h"
#include "Unit_Messages.h"
#include "assert.h"

void Hierarchical_State_Machine::On_Message(const Message *p_Message)
{
    switch (p_Message->GetType())
    {
    case Message::FAULT_TRIGGER:
        p_Current_State->On_Fault_Trigger(*this, p_Message);
        break;

    case Message::SWITCHOVER:
        p_Current_State->On_Switchover(*this, p_Message);
        break;

    case Message::DIAGNOSTICS_PASSED:
        p_Current_State->On_Diagnostics_Passed(*this, p_Message);
        break;

    case Message::DIAGNOSTICS_FAILED:
        p_Current_State->On_Diagnostics_Failed(*this, p_Message);
        break;

    case Message::OPERATOR_INSERVICE:
        p_Current_State->On_Operator_Inservice(*this, p_Message);
        break;

    default:
        assert(false);
        break;
    }
}

void Hierarchical_State_Machine::Inservice::On_Fault_Trigger(
                                   Hierarchical_State_Machine &u, 
                                   const Message *p_Message)
{
    u.Next_State(u.Suspect_State);
    u.Send_Diagnostics_Request();
    u.Raise_Alarm(LOSS_OF_REDUNDANCY);
}


void Hierarchical_State_Machine::Inservice::On_Switchover(
                                   Hierarchical_State_Machine &u, 
                                   const Message *p_Message)
{
    u.Perform_Switchover();
    u.Check_Mate_Status();
    u.Send_Switchover_Response();
}


void Hierarchical_State_Machine::Active::On_Fault_Trigger(
                                   Hierarchical_State_Machine &u, 
                                   const Message *p_Message)
{
    u.Perform_Switchover();
    Inservice::On_Fault_Trigger(u, p_Message);  
}


void Hierarchical_State_Machine::Active::On_Switchover(
                                   Hierarchical_State_Machine &u, 
                                   const Message *p_Message)
{
    Inservice::On_Switchover(u, p_Message);
    u.Next_State(u.Standby_State);
}


void Hierarchical_State_Machine::Standby::On_Switchover(
                                   Hierarchical_State_Machine &u, 
                                   const Message *p_Message)
{
    Inservice::On_Switchover(u, p_Message);
    u.Next_State(u.Active_State);
}

void Hierarchical_State_Machine::Out_Of_Service::On_Operator_Inservice(
                                   Hierarchical_State_Machine &u, 
                                   const Message *p_Message)
{
    // Operator has replaced the card, so abort the current diagnostics
    // and restart new diagnostics on the replaced card.  
    u.Send_Diagnostics_Request();
    u.Send_Operator_Inservice_Response();
    u.Next_State(u.Suspect_State);
}

void Hierarchical_State_Machine::Suspect::On_Diagnostics_Failed(
                                   Hierarchical_State_Machine &u, 
                                   const Message *p_Message)
{
    u.Send_Diagnostics_Failure_Report();
    u.Next_State(u.Failed_State);
}

void Hierarchical_State_Machine::Suspect::On_Diagnostics_Passed(
                                            Hierarchical_State_Machine &u, 
                                            const Message *p_Message)
{
    u.Send_Diagnostics_Pass_Report();
    u.Clear_Alarm(LOSS_OF_REDUNDANCY);
    u.Next_State(u.Standby_State);
}

void Hierarchical_State_Machine::Suspect::On_Operator_Inservice(
                                            Hierarchical_State_Machine &u, 
                                            const Message *p_Message)
{
    u.Abort_Diagnostics();
    Out_Of_Service::On_Operator_Inservice(u, p_Message); 
}