Skip to content

State Machines

We use state machines to model the behavior of our automation system. State machines allow us to define a set of states and transitions between those states based on events and conditions. This approach provides a clear and structured way to manage the complexity of our automation logic. It also allows to easily extend and modify the behavior of the system as we add new sensors, actors, and features.

What is a State Machine?

A state machine is a mathematical model of computation that describes the behavior of a system in terms of states, transitions, and events. It consists of a finite number of states, a set of events that trigger transitions between those states, and a set of actions that are performed during those transitions.

123

import { createMachine, createActor } from 'xstate';

const lightMachine = createMachine({
id: 'light',
initial: 'green',
states: {
    green: {
        on: {
            TIMER: 'yellow'
        }
    },
    yellow: {
        on: {
            TIMER: 'red'
        }
    },
    red: {
        on: {
            TIMER: 'green'
        }
    }
}
});

const actor = createActor(lightMachine);

actor.subscribe((state) => {
console.log(state.value);
});

actor.start();
// logs 'green'

actor.send({ type: 'TIMER' });
// logs 'yellow'

Sources