[NO REPLY] State machines as a construct

A place of insane ideas, nothing to see here.
Post Reply
User avatar
Giovanni
Site Admin
Posts: 14893
Joined: Wed May 27, 2009 8:48 am
Has thanked: 1202 times
Been thanked: 997 times

[NO REPLY] State machines as a construct

Post by Giovanni »

One common problems in embedded programming is to correctly implement state machines, often with the added complexity of interactions with the asynchronous world (IRQ, tasks).

Here is the idea, define a specific construct for implementing state machines of any kind, directly in the language. Consider an extension to the structures definition:

Code: Select all

struct sm {
  state enum st {STOPPED = 0, STARTED, ERROR};
  int i;
  char *message;
  /* other fields */
  ...
  /* this is the new part, attaching actions to variables transitions */
  transition st: STOPPED => STARTED;
    activate_motor();
    if (activation_failure())
      st = ERROR;
  transition st: STARTED => STOPPED;
    stop_motor();
    if (brake_failure())
      st = ERROR;
  transition st: @@ => ERROR;
     report_error();
  default:
    invalid_transition();
};

sm motor1 = {STOPPED, ...};

sm = STARTED; /* starting motor */
sleep(100);
sm = STOPPED; /* stopping motor */


Two new keywords would be required: state and transition. @@ means "any state", => defines a transition. The typical use case is like in ChibiOS HAL drivers, each driver has a state machine, multiple peripherals of the same driver has a separate state machine instance. The XXXDriver structures in HAL could be implemented using this construct.

Syntax is invented and probably could be better or more elegant.

Giovanni
Post Reply