[NO REPLY] State machines as a construct

A place of insane ideas, nothing to see here.
User avatar
Giovanni
Site Admin
Posts: 14444
Joined: Wed May 27, 2009 8:48 am
Location: Salerno, Italy
Has thanked: 1074 times
Been thanked: 921 times
Contact:

[NO REPLY] State machines as a construct

Postby Giovanni » Wed Dec 13, 2017 1:45 pm

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

Return to “Safer C”

Who is online

Users browsing this forum: No registered users and 11 guests