States & Transitions

Based on the tutorials by @thure.

What is a state machine?

A state machine can be thought of as a graph, with nodes, and edges connecting those nodes. The nodes are called states, and the edges are called transitions. Transitions are associated with named events. When you execute the state machine, you create a new state machine instance, and that instance has a particular configuration of states, which is a Set of state ids that the instance is currently in. The state machine receives events, selects transitions from those events, and then flows along the transitions from source to target states, and updates its configuration to the set of target states.

Example: a light switch

Let’s say you have a light switch. Whenever you touch it, it turns on if it was off and off if it was on.

So you have two states: on and off. You also have one event: touch. You can organize this into a statechart like so:

I am a light switch.
You can touch me!
Loading:
    I am a state machine
    I am a light bulb.

    Click to show source code

    Example: two buttons, one light

    Now say we have one of those antique light switches that operates a light with two buttons: one for "off", and one for "on". Pressing "off" while the light is already off does nothing, and the same for the converse.

    For the buttons we have two events, "switch-off" and "switch-on" respectively. For the light we have two states, "on" and "off". That looks like this:

    Switches
    Loading:
      State machine
      Light Bulb

      Click to show source code

      From a design standpoint, this configuration takes a little more effort on the user’s part because the user has to decide what she intends to do, which determines which button to press. But perhaps this light consumes a lot of energy to turn on, so accidentally turning the light off is intentionally designed to require more thought.

      < Previous Page (Why state machines?)Next Page (Doing with SCXML) >