State machines in C - c

What is the best way to write a state machine in C?
I usually write a big switch-case statement in a for(;;), with callbacks to re-enter the state machine when an external operation is finished.
Do you know a more efficient way?

I like the Quantum Leaps approach.
The current state is a pointer to a function that takes an event object as argument. When an event happens, just call the state function with that event; The function can then do its work and transition to another state by just setting the state to another function.
E.g.:
// State type and variable, notice that it's a function pointer.
typedef void (*State)(int);
State state;
// A couple of state functions.
void state_xyz(int event) { /*...*/ }
void state_init(int event) {
if (event == E_GO_TO_xyz) {
// State transition done simply by changing the state to another function.
state = state_xyz;
}
}
// main contains the event loop here:
int main() {
int e;
// Initial state.
state = state_init;
// Receive event, dispatch it, repeat... No 'switch'!
while ((e = wait_for_event()) != E_END) {
state(e);
}
return 0;
}
The QL frameworks provides helpers for extra things like entry/exit/init actions, hierarchical state machines, etc. I highly recommend the book for a deeper explanation and good implementation of this.

The best way is largely subjective, but a common way is to use a "table-based" approach where you map state codes (enums or some other integral type) to function pointers. The function returns your next state and other associated data and you loop through this until the terminal state is reached. This might in fact be what you are describing as your approach above.

That's pretty much the standard approach. If you're interested in studying a well considered library and comparing specifics, take a look at Ragel:
Ragel compiles executable finite state machines from regular languages. Ragel targets C, C++, Objective-C, D, Java and Ruby. Ragel state machines can not only recognize byte sequences as regular expression machines do, but can also execute code at arbitrary points in the recognition of a regular language. Code embedding is done using inline operators that do not disrupt the regular language syntax.

Switch statements are a good way to get started, but they tend to get unwieldy when the FSM gets larger.
A couple related (or duplicate) SO questions with great information and ideas:
state machines tutorials
C state-machine design

I used this pattern. Is there a typical state machine implementation pattern? (check best answer).
But i also add some features
1. Information about previous state.
2. Parameter passing
3. Adding external events like global timeout and "resseting SM"
I found state machines little less cryptic and maintainable.
Anyway, I still think state machines are most difficult and annoying programming task.(I got so far)

An alternative approach is a 2D array that describes for each state/event combination the actions to execute and the next state to go to. This can get trickier to manage when you need to transition to different states depending on 'circumstances', but it can be made to work well. You have an event recognizer function which returns the next event; you have the table where each entry in the table identifies the function to call on receiving the event and the next state to go to - unless the called function overrides that state.
Actually generating such code is fiddlier - it depends on how the FSM is described in the first place. Spotting duplicate actions is often important. Often, you can rely on 'sparse matrix' techniques that do not record error handling explicitly: if the entry logically exists in the sparse matrix, you act on that event/state information, but if the entry does not exist you fall back onto appropriate error reporting and resynchronization code.
A 2D array of pointers to structures can be passed into a generic FSM function; the fact that you write a triple-pointer is enough to make you cautious about what is going on. (I wrote one of those back in March 1986 - I don't have the source for that on disk any more, though I do still have a printout of the document that described it.)

Have a look here: http://code.google.com/p/fwprofile/
It's an open source version (GNU GPLv3) of the state machine implemented
in C. The concept and implementation is well-suited for use in
mission-critical applications. There are deployments in industrial
applications.

I use function pointers and a 2d look-up table where I use the state for one parameter and the event as the other.
I use excel (or any spreadsheet tool) to map a function to every state/event combination.
When an event occurs, I que it up, so then I have something that looks like this
int main(void)
{
StateList currentState = start_up;
EventList currentEvent;
uint8_t stateArray[STATE_COUNT][EVENT_COUNT];
InitializeStateArray(stateArray);
InitializeEventQue();
while(1)
{
currentEvent = GetPriorityEvent();
currentState = (StateList)(*(stateArray[currentState][currentEvent]))();
}
return 1; //should never get here
}
This method essentially forces the developer to consider all possible events in each state, and in my experience makes debugging a little easier.

You can use minimalist uml-state-machine framework implemented in c. It supports both finite and hierarchical state machine. The framework is very minimalist. It has only 3 API's, 2 structures and 1 enumeration.
The State machine is represented by state_machine_t structure. It is an abstract structure that can be inherited to create a state machine.
//! Abstract state machine structure
struct state_machine_t
{
uint32_t Event; //!< Pending Event for state machine
const state_t* State; //!< State of state machine.
};
State is represented by pointer to state_t structure in the framework.
If framework is configured for finite state machine then state_t contains,
typedef struct finite_state_t state_t;
// finite state structure
typedef struct finite_state_t{
state_handler Handler; //!< State handler function (function pointer)
state_handler Entry; //!< Entry action for state (function pointer)
state_handler Exit; //!< Exit action for state (function pointer)
}finite_state_t;
If framework is configured to support hierarchical state machine. It contains additional three members to represent the hierarchical relation between the states.
typedef struct hierarchical_state_t state_t;
//! Hierarchical state structure
typedef struct hierarchical_state_t
{
state_handler Handler; //!< State handler function
state_handler Entry; //!< Entry action for state
state_handler Exit; //!< Exit action for state.
const state_t* const Parent; //!< Parent state of the current state.
const state_t* const Node; //!< Child states of the current state.
uint32_t Level; //!< Hierarchy level from the top state.
}hierarchical_state_t;
The framework provides an API dispatch_event to dispatch the event to the state machine and two API's for the state traversal.
state_machine_result_t dispatch_event(state_machine_t* const pState_Machine[], uint32_t quantity);
state_machine_result_t switch_state(state_machine_t* const pState_Machine, const state_t* pTarget_State);
state_machine_result_t traverse_state(state_machine_t* const pState_Machine, const state_t* pTarget_State);
For more details refer to GitHub project.

check this out "https://github.com/knor12/NKFSMCompiler" it helps generate C Language code for a state machine defined in an scxml or csv file. an example is provided.

Related

How to abstract things away in c without having a bunch of function parameters?

I've been messing around with SDL2 in c and was wondering how to abstract code away without using too many function parameters. For example, in a normal gameplay loop there is usually an input, update, render cycle. Ideally, I would like this to be abstracted as possible so I could have functions called "input", "update", "render", in my loop. How could i do this in c without having those functions take a ludicrous amount of parameters? I know that c++ kind of solves this issue through classes, but I am curious and want to know how to do this in a procedural programming setting.
So far, I can't really think of any way to fix this. I tried looking it up online but only get results for c++ classes. As mentioned before, I want to stick to c because that is what i am comfortable with right now and would prefer to use.
If you have complex state to transport some between calls, put that in a struct. Pass a pointer to that as the sole argument to your functions, out at least as the first of very few.
That is a very common design pattern on C code.
void inputstep(struct state_t* systemstate);
void updatestep(struct state_t* systemstate);
void renderstep(struct state_t* systemstate, struct opengl_context_t* oglctx);
Note also that it is exactly the same, if not even more (due to less safety about pointers), overhead as having a C++ class with methods.
this in a functional programming setting.
Well, C is about as far as you get from a purely functional language, so functional programming paradigms only awkwardly translate. Are you sure you didn't mean "procedural"?
In a functional programming mindset, the state you pass into a function would be immutable or discarded after the function, and the function would return a new state; something like
struct mystate_t* mystate;
...
while(1) {
mystate = inputfunc(mystate);
mystate = updatefunc(mystate);
…
}
Only that in a functional setting, you wouldn't re-assign to a variable, and wouldn't have a while loop like that. Essentially, you wouldn't write C.

Using a while(1) loop as a makeshift state machine in C?

So I have seen that many suggestions on implementing a state machine in C involve a state struct or the like, but I was wondering why we can't just use a while(1) for very simple state machines. For example,
int currentstate = state1;
void state1function(){
dosomething();
if(user chooses to go to state 2){
currentstate = state2;
}
}
int main{
while(1){
if(currentstate == state1){
state1function();
}
else if (currenstate == state2){
state2function();
}
Basically keeping track of the state in a global variable, and in the while loop calling a function depending on the state. This seems simple to me and i don't really see why it wouldn't work.
Can anyone please tell me why something like this would not work/would not be recommended?
Thanks
Sooner or later, using this approach, you will find that it would be convenient to have:
An explicit transition table.
OnEntry(), OnExit(), Do(), OnEvent() functions for each state.
Actions performed on a transition.
Guards. (explicit conditions for transitions to be triggered)
Nested state machines.
Concurrent state machines. Meaning: Multiple FSM running next to each other.
Communicating concurrent, nested state machines.
Somewhere along this ladder of sophistication, you will most likely abandon the brute force style, you started with, which might have looked like the code you gave in your question.
The while(1) construct is quite unrelated to state machines. It is used whenever a single thread of execution (main() or OS threads) are long-running, as they typically are on embedded systems or server-applications. If the application is written in form of a state machine or in other forms, does not really matter.
Depending on the problem you're trying to solve, a global or a static is a straightforward solution. Using a struct comes in handy when you need to manage more than one state machine at a time, and/or when you need to change state from more than one thread or process.
The while loop without wait will consume lot of CPU. I think an event mechanism using mutex or seamphores will be useful.
C is not asynchronous (by default). An infinite loop will just cause your program to "freeze" until the results are done.

Why Function Pointer rather than Calling function Directly

I have come across the function pointers. I know understand how this works. But i am not pretty sure, in what situation it will use. After some google and other search in Stack Overflow. I came know to know that it will use in two case
when callback mechanism is used
Store a array of functions, to call dynamically.
In this case also, why don't we call function directly. In the call back Mechanism also, as particular events occur, callback pointer is assigned to that function(Address). Then that is called. Can't we call function directly rather than using the function pointer. Can some some one tell me, what is the exact usage of Function pointer and in what situation.
Take a look at functions needing a callback, like
bsearch or qsort for the comparator, signal for the handler, or others.
Also, how would you want to program other openly-extensible mechanisms, like C++-like virtual-dispatch (vptr-table with function-pointers and other stuff)?
In short, function-pointers are used for making a function generic by making parts of the behavior user-defined.
One of the situation when function pointers would be useful is when you are trying to implement callback functions.
For example, in a server that I've been implementing in C and libevent accepts a message from clients and determine what to do. Instead of defining hundreds of switch-case blocks, I store function pointer of function to be called in a hash table so the message can be directly mapped to the respective function.
Event handling in libevent API(read about event_new()) also demonstrates the usefulness of having function points in APIs such that users can define their own behaviour given a certain situation and need not to modify the master function's code, which creates flexibility while maintaining certain level of abstraction. This design is also widely used in the Kernel API.
You said:
In the call back Mechanism also, as particular events occur, callback pointer is assigned to that function(Address).
Callback functions are registered at a very different place than where the callback functions are called.
A simple example:
In a GUI, the place where you register a function when a button is pressed is your toplevel application setup. The place where the function gets called is the implementation of the button. They need to remain separate to allow for the user of the button to have the freedom of what they wish to do when a button is pressed.
In general, you need a function pointer when the pointer needs to be stored to be used at a future time.
In the case of a callback situation, including interrupt driven code, a sequence of call backs or interrupts may occur for a single logical process. Say you have a set of functions like step1(), step2(), ... , to perform some process where a common callback is being used to step through a sequence. The initial call sets the callback to step1(), when step1() is called, it changes the pointer to function to step2() and initiates the next step. When that step completes, step2() is called, and it can set a pointer to function to step3(), and so on, depending on how many steps it takes to perform the sequence. I've mostly used this method for interrupt driven code.
Sometimes I use function pointers just to make (as I see it) the code more legible, and easier to change. But this is a matter of taste, there is no one 'correct' way. It's possible that the function pointer code will be slower, but probably only slightly and of course as far as performance goes it's always a matter of measuring, and usually more a matter of choosing better algorithms than of micro-optimisation.
One example is when you have two functions, with identical and long argument lists and sometimes you want to call one and sometimes the other. You could write
if ( condition)
{ one( /* long argument list */);
}
else
{ other( /* long argument list */);
}
or you could write
(condition ? one : other)(/* long argument list */);
I prefer the second as there is only one instance of the long argument list, and so it's easier to get right, and to change.
Another case is implementing state machines; one could write
switch( state)
{ case STATE0: state = state0_fun( input); break;
// etc
}
or
typedef int (*state_f)( void*);
state_f statefs[] = { state0_fun /* etc */}
state = statefs[ state](input);
Again I find the second form more maintainable, but maybe that's just me.

Dealing with game states with different resources in C

I am trying to write a simple game to see how it's done. In my current implementation, I am using array of function pointer's, and my main game loop (stripped) looks like this;
while (stateid != STATE_EXIT) {
handle_events[stateid] ();
logic[stateid] ();
render[stateid]();
change_state(); // change state id, and load new state
}
This way, I can call different functions, depending on the game state. A game state may be something like title, menu or level1 etc. Since each state has different resources, I also have load, and unload functions for each state, here is how change_state looks (stripped)
if (nextstate != STATE_NULL) {
unload_level[stateid] ();
load_level[nextstate]();
stateid = nextstate;
nextstate = STATE_NULL;
}
To handle different resources on different game states, I have made a global void pointer. This global may point to a struct game or struct title depending on the game state. For example, when load_level[STATE_TITLE] is called, a struct title gets created, and global void pointer is set to it's address. So, game state functions can use it like this:
void logic_game()
{
struct game *resources = (struct game *) globalvoidpointer;
// do stuff with resources...
}
But, this whole thing doesn't feel right. It feels overengineered and compilcated to me. How would you suggest I should manage game resources and states? (or say so if this is not overly complicated, and I should stick with it.)
I suspect the design is over-thought.
Set this aspect of the architecture aside for awhile. Then put some effort into sketching out what two different stateid implementations will do for handle_events(), logic(), and render(). You will probably discover that abstractions for resources are not necessary. The stateid itself is probably more than enough to distinguish between what needs to be done.

How to share constant state throughout code without globals

I have a program that uses an external API which uses its own state. The program stores the initial state at the beginning. Afterwards, dozens of functions are invoked using a dispatcher depending on the input. Each of them alters the current state using the API. One of the functions should be able to reset the current state to the initial. Although, that would require access to the variable/constant set at the beginning, which is out of scope in the function.
One solution would be a global, which is considered evil. Another solution could be a function with a static variable to store the initial state at its first call. Calling it again would return the static state. Although, this is not really an improvement.
Is there any clean, maintainable solution to this problem?
Edit: OK, let's say I'll use a const global after all. To illustrate it, I'll use the following code:
extern int get_state();
extern void set_state(int);
const int initial_state = get_state();
int main()
{
while(1) {
// call dispatcher, eventually
break;
}
set_state(initial_state);
return 0;
}
The problem is that the initializer of initial_state must be constant, which get_state() apparently isn't. Is there any way to work around this?
Globals aren't evil (especially if constant).
Any other solution would likely be ugly and would have a better chance of introducing bugs.
You can make use of Singleton design pattern. With this you can share the common state in a cleaner and controlled manner.
Here is the Code for your reference.
In State.h
State *getState(void);
In State.c
static State *g_state;
State* getState(void)
{
if(g_state == NULL) // not initialized
{
// Allocate Memory and initialize it
}
else
{
// operate on it if necessary. Can have mutex, semaphore based on your Use Case.
return g_state;
}
}
Here even though common state is a Global Variable, it is not accessible outside getState() function, hence no evil of using Global variable!!
Shash

Resources