Practical UML Statecharts in C/C++

Miro Samek

Mentioned 7

Explains how to streamline an embedded code project through the use of UML (unified modeling language) statecharts as a framework for creating and maintaining efficient and maintainable systems, describing the new features and functions of the open-source software framework, while discussing statecharts, design applications, and how to code directly into C/C++. Original. (Advanced)

More on Amazon.com

Mentioned in questions and answers.

I'm looking for ways to de-spaghttify my front-end widget code. It's been suggested that a Finite State Machine is the right way to think about what I'm doing. I know a State Machine paradigm can be applied to almost any problem. I'm wondering if there are some experienced UI programmers who actually make a habit of this.

So, the question is -- do any of you UI programmers think in terms of State Machines in your work? If so, how?

thanks, -Morgan

We were just talking about Horrocks' Constructing the User Interface with Statecharts, prices 2nd-hand range from $250 up to nearly $700. Our software development manager rates it as one of the most important books he's got (sadly, he lives on the other side of the world).

Samek's books on statecharts draw significantly from this work although in a slightly different domain and reportedly not as clear. "Practical UML Statecharts in C/C++Event-Driven Programming for Embedded Systems" is also available on Safari.

Horrocks is cited quite heavily - there are twenty papers on the ACM Portal so if you have access there you might find something useful.

There's a book and software FlashMX for Interactive Simulation. They have a PDF sample chapter on statecharts.

Objects, Components, and Frameworks with UML: The Catalysis(SM) Approach has a chapter on Behaviour Models which includes about ten pages of useful examples of using statecharts (I note that it is available very cheaply second hand). It is rather formal and heavy going but that section is easy reading.

Well, initial reason I ask this question is I need from time to time learning materials for struggling C / C++ developer who is in general competent but needs to improve some aspect directly related to embedded system software development (telecom mainly). And I found I have not so many useful things to recommend.

Could community help with good references (I think this is more related to junior / middle level but I suppose good materials for mature engineers are even more valuable)?

Obvious areas to cover are:

  • Software development in limited resources conditions.
  • Low level programming strategies.
  • Software development before hardware is available.
  • Special debugging tricks.
  • Architecture dependent techniques.
  • Distributed programming.

Thank you in advance, let us help ourselves ;-).

I have worked extensively on AVR microcontrollers. I haven't had a proper OS course at UNI..not from a CS branch, but I want a book that gives me generic OS concepts as well as RTOS concepts for embedded systems. Any suggestion?. Something that details a particular OS like TinyOS or FemtoOS would be nice, but I want something with API based examples/codes as well.

Any suggestions ?

At least 3 (well, 4) books come to mind immediately:

I have a statemachine in a real-time system with very few (3) states.

typedef enum {
    STATE1,
    STATE2,
    STATE3
} state_t;

However, the transitions between those states need considerable time and have their own subdivisions. So I have two choices, either I extend the main statemachine such that all the intermediate states are represented:

typedef enum {
    STATE1,
    STATE1_PREPARE_TRANSITION_TO_STATE2,
    STATE1_DO_TRANSITION_TO_STATE2,
    STATE1_PREPARE_TRANSITION_TO_STATE3,
    STATE1_DO_TRANSITION_TO_STATE3,
    STATE2,
    ...
} state_t;

or I create a nested statemachine for the relevant main states:

typedef enum {
    STATE1_NOT_ACTIVE,
    STATE1_NORMAL,
    STATE1_PREPARE_TRANSITION_TO_STATE2,
    STATE1_DO_TRANSITION_TO_STATE2,
    STATE1_PREPARE_TRANSITION_TO_STATE3,
    STATE1_DO_TRANSITION_TO_STATE3
} sub_state1_t;
...

Both possibilities have their advantages and drawbacks. The big statemachine gets messy and complicated very easily. However, having all the states consistent in the second case isn't trivial either and many functions would need information about both the global state and the substates.

I'd like to avoid complicated code which has to handle several parallel states, like:

if ((global_state == STATE1) &&
    (sub_state_1 == STATE1_DO_TRANSITION_TO_STATE2))
{
    ...
    if (transition_xy_done(...))
    {
        global_state = STATE2;
        sub_state_1 = STATE1_NOT_ACTIVE;
        sub_state_2 = STATE2_NORMAL;
    }
}

What is the general best approach for such a problem: many small and nested statemachines (with many invalid combinations), one big statemachine or anything else?

First, I want to commend you for recognizing what's happening and making these states explicit (since they are in fact additional states in your model, not really transitions with an action). Far too often I see state machines that end up like your last example (that you want to avoid). When you have tests for 'additional' state variables inside your event handlers, it's a sign that your state machine has more states that you've really put into the design - those show be reflected in the design, not jammed into the existing state's event handlers with a bunch of spaghetti coded checks for additional 'state' encoded in global variables.

There are several frameworks for C++ that model hierarchical state machines - HSMs - (which is what your nested state machine idea sounds like), but the only one I'm aware of that supports straight C is Quantum Framework, and I think that buying into that would probably mean a decent level of commitment (ie., it's probably not a simple change). However, if you wnt to look into this possibility, Samek has written a lot of articles (and a book) about how to support HSMs in C.

However, if you don't need some of the more sophisiticated parts of the HSM models (such as events that aren't handled by the 'innermost' state get bubbled up to be possibly handled by parent states, full enter and exit support for the entire state hierarchy), then it's pretty easy to support nested state machines just as completely independant state machines that happen to start and stop when a parent state is entered/exited.

The big state machine model is probably a bit easier to implement (it's just several more states in your existing framework). I'd suggest that if adding the states to your current state machine mode doesn't make the model too complex, then just go with that.

In other words, let what works best for your model drive how you implement the state machine in software.

Ok let's say I have 2 states (s1 and s2). s1 can go to s2 with event e1 and s2 can go to s1 with event e2.

Now, let's also assume that e1 and e2 are only fired from s1 and s2 respectively if certain conditions apply.

so in main() I will first of start by starting the state machine using start() then Ill have an infinite loop. In that loop I need to be able to keep going in the state machine at the same state I left it. How can I do that?

i.e. Let say I was in s2 and I execute all the code in s2 and I did not fire e2 then I left the state and I hit the end of my while loop now I want to go back to s2 to continue from there and see if this time e2 will fire.

The short answer is: make a third kind of event which causes an internal transition in both states and post it in your endless loop in main.

The long answer starts with the question why would anyone want to do that? At least in my experience state machines should be more of an event driven concept which react to OUTSIDE events. Using polling (which it looks like what your after) inside a state machine is not really what state machines are for. I would do the polling outside the state machine (in main in your case) and when I do get an event then post that to the state machine.

Its also common for a state to set a timer (again outside the state machine) to post a "timeout event" (or any other event for that matter) after a certain duration of time. Its good practice in my mind to cancel that request on exiting the state which requested it. Even if it seems useless in some cases because there is no reason to leave the state now it sure helps the poor maintenance programmer who implements a new event exiting the state and then tears his hair out wondering why he got a "timeout event" three state transitions later.

If you are new to state machines I would highly suggest Miro Samek's book: http://www.amazon.com/exec/obidos/ASIN/0750687061/quantumleap06-20

i'm learning about Finite State MAchine(FSM)..can you help me with how the machine operates and the functional state diagram about the operation of this machine using FSM.

I can highly recommend the book Practical UML Statecharts in C/C++, Second Edition: Event-Driven Programming for Embedded Systems if you don't find internet resources sufficient.

The author have implemented a state machine framework that might be suitable for your application as well (I have not used the framework myself though).

I need to make a state machine for a hardware device. It will have more than 25 states and I am not sure what design to apply.

Because I am using C++11 I thought of using OOP and implementing it using the State Pattern, but I don't think it is appropriate for the embedded system.

Should it be more like a C style design ? I haven't code it one before. Can someone give me some pointers on what is the best suited design ?

System information:

ARM Cortex-M4  
1 MB Flash  
196 KB Ram

I also saw this question, the accepted answers points to a table design, the other answer to a State pattern design.

Consider the QP active object framework, a framework for implementing hierarchical state machines in embedded systems. It's described in the book, Practical UML Statecharts in C/C++: Event Driven Programming for Embedded Systems by Miro Samek. Also, Chapter 3 of the book describes more traditional ways of implementing state machines in C and C++.