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

Design

UML Statecharts at $10.99


Coding a Statechart in C

Contrary to popular belief, you don't need big code-synthesizing tools to translate UML statecharts to efficient and highly maintainable code. The implementation strategy I use to hand-code the PELICAN crossing statechart in Figure 2 in portable C is based on QP-nano, a generic "event processor" from my company Quantum Leaps. Actually QP-nano is more than just an event processor; it is a complete platform for executing concurrent state machines. Besides the optimized hierarchical event processor, QP-nano also provides event passing mechanism, event queuing, time event generation (timers), and a simple non-preemptive, prioritized scheduler to execute state machines in run-to-completion (RTC) fashion. All these services require about 1300 bytes of code (ROM) and just a few bytes of RAM on the 8051.

QP-nano has been designed for small systems with limited RAM. In this minimal version, events are represented as structures containing the byte-wide enumerated type of the event, such as TIMEOUT or PED_WAITING, which in the UML is called the "signal." Optionally, QP-nano lets every event have a single scalar event parameter. Event parameters are useful to convey the quantitative information associated with the event. For example, an ADC conversion might generate an event with the signal ADC_READY and the parameter containing the value produced by the ADC.

Each state in QP-nano is represented as a C function called a "state handler" function. The job of QP-nano is to invoke these state handler functions in the right order to process events according to the UML semantics.

A state handler function is a regular C function that takes the state machine pointer as the argument and returns a pointer to another state handler function, which is typedefed as QSTATE in the QP-nano header file qpn.h. You need to structure your state handler functions such that they return the pointer to the superstate handler, if they don't handle the current event, or a NULL-pointer, if they handle the current event. QP-nano uses this information to "learn" about the nesting of states to process events hierarchically and correctly execute state transitions.

To determine what elements belong a given state handler function, you first need to look up the state in the diagram and follow around the state's boundary. You need to implement all transitions originating at the boundary, any entry and exit actions defined directly in this state, as well as all internal transitions enlisted directly in the state. Additionally, if there is an initial transition embedded directly in the state, you need to implement it as well. You don't worry about any substates nested in the given state. These substates are implemented in their own state handler functions.

Take, for example, the state carsGreen in Figure 2. This state has one transition TIMEOUT originating at its boundary, an exit action and the initial transition to the substate carsGreenNoPed. The state carsGreen nests directly inside carsEnabled.

Listing One shows the state handler function Pelican_carsGreen() corresponding to the PELICAN state carsGreen. The state handler takes only one argument: the state-machine pointer; Pelican* in this case (1).

By convention, I always name this argument "me". (If you are familiar with C++, you'll recognize that me corresponds to the this pointer in C++.) Generally, every state handler is structured as a big switch that discriminates based on the signal of the current event. To reduce the number of arguments of the state handler function, QP-nano stores the current event in the state machine object pointed to by the me pointer. For convenience, QP-nano provides the macro Q_SIG() to access the signal of the event (2). Each case is labeled by an enumerated signal and terminates with return (QSTATE)0. Returning a zero-pointer from a state handler informs the event processor that the particular event has been processed. On the other hand, if no case executes, the state handler exits through the final return statement, which returns the pointer to the superstate handler function (QSTATE)&Pelican_carsEnabled in this case (11). Please note that the final return statement from a state handler function is the only place where you specify the hierarchy of states. Therefore, this one line of code represents the single point of maintenance for changing the nesting level of a given state.

(1) QSTATE Pelican_carsGreen(Pelican *me) {
(2)     switch (Q_SIG(me)) { /* switch on signal of current event */
(3)         case Q_ENTRY_SIG: {         /* entry action */
                QActive_arm((QActive *)me, CARS_GREEN_MIN_TOUT);
                BSP_signalCars(CARS_GREEN);
(4)             return (QSTATE)0;       /* event handled */
          }
(5)        case Q_INIT_SIG: {                  
(6)           Q_INIT(&Pelican_carsGreenNoPed);/* initial transition */
(7)          return (QSTATE)0;               /* event handled */
          }
(8)       case Q_TIMEOUT_SIG: {
(9)          Q_TRAN(&Pelican_carsGreenInt);    /* state transition */
(10)          return (QSTATE)0;             /* event handled */
            }
        }
(11)    return (QSTATE)&Pelican_carsEnabled;    /* the superstate */
    }

Listing One: State-handler function for the "carsGreen" state.

At the label (3) in Listing One, you can see how to code the entry action. QP-nano provides a reserved signal Q_ENTRY_SIG (and also Q_EXIT_SIG for exit actions) that the event processor sets in the state machine before calling the appropriate state handler function to execute the state entry actions. Therefore, to code a state entry action, you provide a case statement labeled with signal Q_ENTRY_SIG, enlist all the actions you want to execute upon the entry to the state, and terminate the actions with return (QSTATE)0 (4). Coding an exit action is identical, except that you provide a case statement labeled with signal Q_EXIT_SIG.

Every composite state (a state with substates) can have its own initial transition, which in the diagrams is represented as an arrow originating from a black ball. For example, state carsGreen in Figure 2 has such a transition to the substate carsGreenNoPed. QP-nano provides a reserved signal Q_INIT_SIG that the event processor sets in the state machine before calling the state handler function to execute the initial transition. At the label (5) of Listing One you can see how to code the initial transition. You provide a case statement labeled with signal Q_INIT_SIG, enlist all the actions you want to execute upon the initial transition, and then designate the target substate with the Q_INIT() macro (6). You terminate the case statement with return (QSTATE)0, which informs the event processor that the initial transition has been handled (7).

Finally, at the label (8) in Listing One, you can see how to code a regular state transition. You provide a case statement labeled with the triggering signal (Q_TIMEOUT_SIG in this case), enlist the actions, and then designate the target state with the Q_TRAN() macro provided by QP-nano (9). You terminate the case statement with return (QSTATE)0, which informs the event processor that the event has been handled (10).

And this is about all you need to know to code any state (To conserve stack space, QP-nano can handle up to four levels of state nesting). The PELICAN crossing source code (pelican.c) accompanying this article provides more examples, such as coding internal transitions and transitions with guards.


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.