Author Topic: Hierarchical state machines, does anyone have a pattern or framework?  (Read 1478 times)

0 Members and 1 Guest are viewing this topic.

Offline jnzTopic starter

  • Frequent Contributor
  • **
  • Posts: 593
I have a project I'm working on, it has like 5 statemachines in it. And now I need another one to handle some protocol packet assembly and request/responses. I think instead of making another bad implementation I'd like to try and find something "more standard" that is either a design pattern with examples and comments, or a framework for this. There isn't a lot out there for C.

I've found Quantum Leaps which is alright, and seems like it can be used in a way that lets me keep my existing code as is.

Also uFSM was on hackernews the other day, but it's 11 days old, has no comments, and I'm not sure I can be on something that might be a timesuck.

So.... What I'm looking for is a way to implement state charts, hierarchical would be nice, a clear manual transition table or a reliable automatically generated one, IDK.... What do you guys use?
 

Offline obiwanjacobi

  • Frequent Contributor
  • **
  • Posts: 988
  • Country: nl
  • What's this yippee-yayoh pin you talk about!?
    • Marctronix Blog
As discussed here there are several options.

I lean toward using code instead of tables or switch statements (directly).
For that purpose I use a couple of macro's found here.
You would write the statemachine as a sequence of code statements, using normal control flow (if/else/switch etc) and 'return' from the 'task' using one of the Task_Yield macros.

These 'tasks' can be nested (use a C++ class for each task) and pretty complex, but still readable/understandable.
Truth be told, I have never used it for more than 2 levels deep, though.

[2c]
Arduino Template Library | Zalt Z80 Computer
Wrong code should not compile!
 

Offline jnzTopic starter

  • Frequent Contributor
  • **
  • Posts: 593
That discussion was on machine yea, but I didn't see much about HSMs.

Do you have a rough example of that code you linked to? I'm not exactly understanding some of it.
 

Offline obiwanjacobi

  • Frequent Contributor
  • **
  • Posts: 988
  • Country: nl
  • What's this yippee-yayoh pin you talk about!?
    • Marctronix Blog
Here is an implementation of a task. The Task_Begin(Execute) is the interesting bit.
You can see you can use normal flow control to write out the logic. Here I'm using a while-loop.

You would call it like this (Arduino).
Here I instantiate 2 instances of the (counter) task and call them repeatedly in the main loop.
You probably would not want to instantiate you statemachine more than once, though.

Each sub-state in your hierarchical statemachine would be another task class where you write out its logic in the task-method (here Execute).

Hope it helps.


Arduino Template Library | Zalt Z80 Computer
Wrong code should not compile!
 


Share me

Digg  Facebook  SlashDot  Delicious  Technorati  Twitter  Google  Yahoo
Smf