Simvik

Pass events up the hierarchy

Find the state that handles an event: the current state, or the nearest ancestor that does. A medium embedded C problem (Hierarchical state machines), run…

medium · Hierarchical state machines · fsm · hierarchical · pointers

In a hierarchical state machine, an event the current state does not handle is passed to its parent, then the grandparent, and so on. This lets common behaviour (every running state stops when the door opens; every state powers off) be written once.

Write handler_for(current, event): return the first state, starting at current and walking up through parent, whose handles mask includes event; or NULL if no state handles it (the event is ignored).

Also write depth(s): the number of ancestors above s (0 for the top state).

Starter code

const state_t *handler_for(const state_t *current, int event) {
  return (current->handles & (1u << event)) ? current : NULL;
}

int depth(const state_t *s) {
  (void)s;
  return 0;
}

Example tests

Handled where it is

show(&heating, 4);
show(&idle, 1);

Expected output:

in heating (depth 2), event 4: heating
in idle (depth 1), event 1: idle

Handled by a parent

show(&heating, 3);
show(&heating, 0);
show(&idle, 0);

Expected output:

in heating (depth 2), event 3: running
in heating (depth 2), event 0: on
in idle (depth 1), event 0: on

Learn it first