Erlang Expert · Lesson 1 · On the house

gen_statem state machines

Model protocols as explicit states with gen_statem, state_functions, and state timeouts. Lesson 1 is free — on the house.

Lessons · Erlang Expert · Lesson 1 of 10 · On the house

gen_statem state machines

Model protocols as explicit states with gen_statem, state_functions, and state timeouts.

Illustration for Erlang
Lesson 1 is on the house.

gen_statem is OTP's state-machine behaviour. With callback_mode() -> state_functions. each state is a function: locked(EventType, Event, Data).

Return {next_state, NewState, NewData} to transition, or {keep_state, Data} to stay. Replies to calls are actions: [{reply, From, ok}].

State timeouts ({state_timeout, Ms, Msg}) are cancelled automatically when the state changes, perfect for 'relock after 5 s'.

handle_event_function mode uses one callback for all states when state is complex data.

Explicit states make protocols (door locks, TCP handshakes, payment flows) auditable.

gen_statem

-module(door).
-behaviour(gen_statem).
-export([main/0, callback_mode/0, init/1, locked/3, open/3]).

callback_mode() -> state_functions.
init(Code) -> {ok, locked, #{code => Code, tries => 0}}.

locked({call, From}, {enter, Code}, D = #{code := Code}) ->
    {next_state, open, D#{tries := 0}, [{reply, From, opened}, {state_timeout, 30, relock}]};
locked({call, From}, {enter, _}, D = #{tries := T}) ->
    {keep_state, D#{tries := T + 1}, [{reply, From, {wrong, T + 1}}]};
locked({call, From}, state, D) -> {keep_state, D, [{reply, From, locked}]}.

open(state_timeout, relock, D) -> {next_state, locked, D};
open({call, From}, state, D) -> {keep_state, D, [{reply, From, open}]}.

main() ->
    {ok, P} = gen_statem:start(?MODULE, 1234, []),
    io:format("~p~n", [gen_statem:call(P, {enter, 1111})]),
    io:format("~p~n", [gen_statem:call(P, {enter, 1234})]),
    io:format("~p~n", [gen_statem:call(P, state)]),
    timer:sleep(60),
    io:format("~p~n", [gen_statem:call(P, state)]).
Match this when you type.

Quiz

In state_functions mode, what is each state?

Quiz

What happens to a state_timeout when the state changes?

Quiz

How does a gen_statem reply to a call?

Quiz

What's the state after the 30 ms timeout?

Check

Match the still for: gen_statem state machines.

Open-book: the answers are on this page. Pass every quiz and check (5) to mark the lesson done. This visit: 0/5.