1gen_statem(3)              Erlang Module Definition              gen_statem(3)
2
3
4

NAME

6       gen_statem - Generic state machine behavior.
7

DESCRIPTION

9       gen_statem provides a generic state machine behaviour that for new code
10       replaces its predecessor gen_fsm since Erlang/OTP 20.0. The gen_fsm be‐
11       haviour remains in OTP "as is".
12
13   Note:
14       If you are new to gen_statem and want an overview of concepts and oper‐
15       ation the section gen_statem Behaviour  located  in  the  User's  Guide
16       OTP  Design  Principles   is  recommended to read before this reference
17       manual, possibly after the Description section you are reading here.
18
19
20       This reference manual contains type descriptions generated  from  types
21       in the gen_statem source code, so they are correct. However, the gener‐
22       ated descriptions also reflect  the  type  hierarchy,  which  sometimes
23       makes it hard to get a good overview. If so, see the section gen_statem
24       Behaviour  in the  OTP Design Principles  User's Guide.
25
26   Note:
27
28         * This behavior appeared in Erlang/OTP 19.0.
29
30         *
31            In OTP 19.1 a backwards incompatible change of  the  return  tuple
32           from  Module:init/1  was  made  and the mandatory callback function
33           Module:callback_mode/0 was introduced.
34
35         *
36            In OTP 20.0  generic time-outs  were added.
37
38         *
39            In OTP 22.1 time-out content update and explicit  time-out  cancel
40           were added.
41
42         *
43            In OTP 22.3 the possibility to change the callback module with ac‐
44           tions change_callback_module,  push_callback_module  and  pop_call‐
45           back_module, was added.
46
47       gen_statem has got the same features that gen_fsm had and adds some re‐
48       ally useful:
49
50         * Co-located state code
51
52         * Arbitrary term state
53
54         * Event postponing
55
56         * Self-generated events
57
58         * State time-out
59
60         * Multiple generic named time-outs
61
62         * Absolute time-out time
63
64         * Automatic state enter calls
65
66         *
67            Reply from other state than the request, sys traceable
68
69         * Multiple sys traceable replies
70
71         * Changing the callback module
72
73       Two callback modes are supported:
74
75         * One for finite-state machines (gen_fsm like),  which  requires  the
76           state  to be an atom and uses that state as the name of the current
77           callback function.
78
79         * One that allows the state to be any term and that uses one callback
80           function for all states.
81
82       The  callback model(s) for gen_statem differs from the one for gen_fsm,
83       but it is still fairly easy to  rewrite from  gen_fsm to gen_statem.
84
85       A generic state machine server process (gen_statem)  implemented  using
86       this  module  has  a  standard  set of interface functions and includes
87       functionality for tracing and error reporting. It also fits into an OTP
88       supervision tree. For more information, see OTP Design Principles.
89
90       A  gen_statem  assumes  all  specific parts to be located in a callback
91       module exporting a predefined set of functions.  The  relationship  be‐
92       tween the behavior functions and the callback functions is as follows:
93
94       gen_statem module            Callback module
95       -----------------            ---------------
96       gen_statem:start
97       gen_statem:start_monitor
98       gen_statem:start_link -----> Module:init/1
99
100       Server start or code change
101                             -----> Module:callback_mode/0
102
103       gen_statem:stop       -----> Module:terminate/3
104
105       gen_statem:call
106       gen_statem:cast
107       gen_statem:send_request
108       erlang:send
109       erlang:'!'            -----> Module:StateName/3
110                                    Module:handle_event/4
111
112       -                     -----> Module:terminate/3
113
114       -                     -----> Module:code_change/4
115
116       Events  are  of different types, so the callback functions can know the
117       origin of an event and how to respond.
118
119       If a callback function fails or returns a  bad  value,  the  gen_statem
120       terminates,  unless  otherwise  stated.  However, an exception of class
121       throw is not regarded as an error but as a valid return from all  call‐
122       back functions.
123
124       The state callback for a specific state in a gen_statem is the callback
125       function that is called for all events in this state.  It  is  selected
126       depending  on which callback mode that the callback module defines with
127       the callback function Module:callback_mode/0.
128
129       When the callback mode is state_functions, the state must  be  an  atom
130       and  is  used  as the state callback name; see Module:StateName/3. This
131       co-locates all code for  a  specific  state  in  one  function  as  the
132       gen_statem  engine branches depending on state name. Note the fact that
133       the callback function Module:terminate/3 makes the state name terminate
134       unusable in this mode.
135
136       When  the  callback mode is handle_event_function, the state can be any
137       term and the state callback name is Module:handle_event/4.  This  makes
138       it easy to branch depending on state or event as you desire. Be careful
139       about which events you handle in which states so that you do not  acci‐
140       dentally postpone an event forever creating an infinite busy loop.
141
142       When  gen_statem  receives  a  process  message it is converted into an
143       event and the state callback is called with the event as two arguments:
144       type  and  content.  When the state callback has processed the event it
145       returns to gen_statem which does a  state  transition.  If  this  state
146       transition is to a different state, that is: NextState =/= State, it is
147       a state change.
148
149       The state callback may return transition actions for gen_statem to exe‐
150       cute   during   the  state  transition,  for  example  to  reply  to  a
151       gen_statem:call/2,3.
152
153       One of the possible transition  actions  is  to  postpone  the  current
154       event.  Then it is not retried in the current state. The gen_statem en‐
155       gine keeps a queue of events divided into the postponed events and  the
156       events  still  to process. After a state change the queue restarts with
157       the postponed events.
158
159       The gen_statem event queue model is sufficient to  emulate  the  normal
160       process  message queue with selective receive. Postponing an event cor‐
161       responds to not matching it in a receive statement, and changing states
162       corresponds to entering a new receive statement.
163
164       The  state  callback  can  insert  events  using the transition actions
165       next_event and such an event is inserted in the event queue as the next
166       to call the state callback with. That is, as if it is the oldest incom‐
167       ing event. A dedicated event_type()  internal  can  be  used  for  such
168       events making them impossible to mistake for external events.
169
170       Inserting  an  event  replaces the trick of calling your own state han‐
171       dling functions that you often would have to resort to in, for example,
172       gen_fsm to force processing an inserted event before others.
173
174       The  gen_statem engine can automatically make a specialized call to the
175       state callback whenever a new state is entered; see state_enter(). This
176       is  for  writing code common to all state entries. Another way to do it
177       is to explicitly insert an event at the state transition, and/or to use
178       a  dedicated  state transition function, but that is something you will
179       have to remember at every state transition to the  state(s)  that  need
180       it.
181
182   Note:
183       If  you  in gen_statem, for example, postpone an event in one state and
184       then call another state callback of yours, you have not  done  a  state
185       change  and  hence the postponed event is not retried, which is logical
186       but can be confusing.
187
188
189       For the details of a state transition, see type transition_option().
190
191       A gen_statem handles system messages as described in sys. The sys  mod‐
192       ule can be used for debugging a gen_statem.
193
194       Notice that a gen_statem does not trap exit signals automatically, this
195       must be  explicitly  initiated  in  the  callback  module  (by  calling
196       process_flag(trap_exit, true).
197
198       Unless otherwise stated, all functions in this module fail if the spec‐
199       ified gen_statem does not exist or if bad arguments are specified.
200
201       The gen_statem process can go  into  hibernation;  see  proc_lib:hiber‐
202       nate/3. It is done when a state callback or Module:init/1 specifies hi‐
203       bernate in the returned Actions list. This feature can be useful to re‐
204       claim process heap memory while the server is expected to be idle for a
205       long time. However, use this feature with care, as hibernation  can  be
206       too costly to use after every event; see erlang:hibernate/3.
207
208       There  is  also  a  server  start option {hibernate_after, Timeout} for
209       start/3,4, start_monitor/3,4, start_link/3,4 or enter_loop/4,5,6,  that
210       may be used to automatically hibernate the server.
211
212       If the gen_statem process terminates, e.g. as a result of a function in
213       the callback module returning {stop,Reason}, an exit signal  with  this
214       Reason  is  sent  to  linked processes and ports. See  Processes in the
215       Reference Manual for details regarding error handling using  exit  sig‐
216       nals.
217

EXAMPLE

219       The  following  example  shows a simple pushbutton model for a toggling
220       pushbutton implemented with callback mode state_functions. You can push
221       the  button  and it replies if it went on or off, and you can ask for a
222       count of how many times it has been pushed to switch on.
223
224       The following is the complete callback module file pushbutton.erl:
225
226       -module(pushbutton).
227       -behaviour(gen_statem).
228
229       -export([start/0,push/0,get_count/0,stop/0]).
230       -export([terminate/3,code_change/4,init/1,callback_mode/0]).
231       -export([on/3,off/3]).
232
233       name() -> pushbutton_statem. % The registered server name
234
235       %% API.  This example uses a registered name name()
236       %% and does not link to the caller.
237       start() ->
238           gen_statem:start({local,name()}, ?MODULE, [], []).
239       push() ->
240           gen_statem:call(name(), push).
241       get_count() ->
242           gen_statem:call(name(), get_count).
243       stop() ->
244           gen_statem:stop(name()).
245
246       %% Mandatory callback functions
247       terminate(_Reason, _State, _Data) ->
248           void.
249       code_change(_Vsn, State, Data, _Extra) ->
250           {ok,State,Data}.
251       init([]) ->
252           %% Set the initial state + data.  Data is used only as a counter.
253           State = off, Data = 0,
254           {ok,State,Data}.
255       callback_mode() -> state_functions.
256
257       %%% state callback(s)
258
259       off({call,From}, push, Data) ->
260           %% Go to 'on', increment count and reply
261           %% that the resulting status is 'on'
262           {next_state,on,Data+1,[{reply,From,on}]};
263       off(EventType, EventContent, Data) ->
264           handle_event(EventType, EventContent, Data).
265
266       on({call,From}, push, Data) ->
267           %% Go to 'off' and reply that the resulting status is 'off'
268           {next_state,off,Data,[{reply,From,off}]};
269       on(EventType, EventContent, Data) ->
270           handle_event(EventType, EventContent, Data).
271
272       %% Handle events common to all states
273       handle_event({call,From}, get_count, Data) ->
274           %% Reply with the current count
275           {keep_state,Data,[{reply,From,Data}]};
276       handle_event(_, _, Data) ->
277           %% Ignore all other events
278           {keep_state,Data}.
279
280
281       The following is a shell session when running it:
282
283       1> pushbutton:start().
284       {ok,<0.36.0>}
285       2> pushbutton:get_count().
286       0
287       3> pushbutton:push().
288       on
289       4> pushbutton:get_count().
290       1
291       5> pushbutton:push().
292       off
293       6> pushbutton:get_count().
294       1
295       7> pushbutton:stop().
296       ok
297       8> pushbutton:push().
298       ** exception exit: {noproc,{gen_statem,call,[pushbutton_statem,push,infinity]}}
299            in function  gen:do_for_proc/2 (gen.erl, line 261)
300            in call from gen_statem:call/3 (gen_statem.erl, line 386)
301
302
303       To compare styles, here follows the same example  using  callback  mode
304       handle_event_function,  or  rather  the  code to replace after function
305       init/1 of the pushbutton.erl example file above:
306
307       callback_mode() -> handle_event_function.
308
309       %%% state callback(s)
310
311       handle_event({call,From}, push, off, Data) ->
312           %% Go to 'on', increment count and reply
313           %% that the resulting status is 'on'
314           {next_state,on,Data+1,[{reply,From,on}]};
315       handle_event({call,From}, push, on, Data) ->
316           %% Go to 'off' and reply that the resulting status is 'off'
317           {next_state,off,Data,[{reply,From,off}]};
318       %%
319       %% Event handling common to all states
320       handle_event({call,From}, get_count, State, Data) ->
321           %% Reply with the current count
322           {next_state,State,Data,[{reply,From,Data}]};
323       handle_event(_, _, State, Data) ->
324           %% Ignore all other events
325           {next_state,State,Data}.
326
327

DATA TYPES

329       server_name() =
330           {global, GlobalName :: term()} |
331           {via, RegMod :: module(), Name :: term()} |
332           {local, atom()}
333
334              Name specification to use when starting a gen_statem server. See
335              start_link/3 and server_ref() below.
336
337       server_ref() =
338           pid() |
339           (LocalName :: atom()) |
340           {Name :: atom(), Node :: atom()} |
341           {global, GlobalName :: term()} |
342           {via, RegMod :: module(), ViaName :: term()}
343
344              Server specification to use when addressing a gen_statem server.
345              See call/2 and server_name() above.
346
347              It can be:
348
349                pid() | LocalName:
350                  The gen_statem is locally registered.
351
352                {Name,Node}:
353                  The gen_statem is locally registered on another node.
354
355                {global,GlobalName}:
356                  The gen_statem is globally registered in global.
357
358                {via,RegMod,ViaName}:
359                  The gen_statem is registered in an alternative process  reg‐
360                  istry.  The  registry  callback  module  RegMod is to export
361                  functions        register_name/2,         unregister_name/1,
362                  whereis_name/1,  and  send/2,  which  are to behave like the
363                  corresponding functions in global. Thus, {via,global,Global‐
364                  Name} is the same as {global,GlobalName}.
365
366       start_opt() =
367           {timeout, Time :: timeout()} |
368           {spawn_opt, [proc_lib:start_spawn_option()]} |
369           enter_loop_opt()
370
371              Options  that  can  be  used  when  starting a gen_statem server
372              through, for example, start_link/3.
373
374       start_ret() = {ok, pid()} | ignore | {error, term()}
375
376              Return value from the start() and  start_link()  functions,  for
377              example, start_link/3.
378
379       start_mon_ret() =
380           {ok, {pid(), reference()}} | ignore | {error, term()}
381
382              Return value from the start_monitor() functions.
383
384       enter_loop_opt() =
385           {hibernate_after, HibernateAfterTimeout :: timeout()} |
386           {debug, Dbgs :: [sys:debug_option()]}
387
388              Options  that  can  be  used  when  starting a gen_statem server
389              through, enter_loop/4-6.
390
391                hibernate_after:
392                  HibernateAfterTimeout specifies that the gen_statem  process
393                  awaits  any  message  for HibernateAfterTimeout milliseconds
394                  and if no message is received, the process goes into  hiber‐
395                  nation automatically (by calling proc_lib:hibernate/3).
396
397                debug:
398                  For  every  entry in Dbgs, the corresponding function in sys
399                  is called.
400
401       from() = {To :: pid(), Tag :: term()}
402
403              Destination to use when replying through, for example,  the  ac‐
404              tion()  {reply,From,Reply}  to  a  process  that  has called the
405              gen_statem server using call/2.
406
407       state() = state_name() | term()
408
409              If the callback mode is handle_event_function, the state can  be
410              any  term. After a state change (NextState =/= State), all post‐
411              poned events are retried.
412
413       state_name() = atom()
414
415              If the callback mode is state_functions, the state  must  be  an
416              atom.  After a state change (NextState =/= State), all postponed
417              events are retried. Note that the state terminate is not  possi‐
418              ble  to  use  since  it would collide with the optional callback
419              function Module:terminate/3.
420
421       data() = term()
422
423              A term in which the state machine implementation is to store any
424              server  data  it  needs.  The  difference  between  this and the
425              state() itself is that a change in  this  data  does  not  cause
426              postponed  events to be retried. Hence, if a change in this data
427              would change the set of events that are handled, then that  data
428              item is to be made a part of the state.
429
430       event_type() =
431           external_event_type() | timeout_event_type() | internal
432
433              There  are 3 categories of events: external, timeout, and inter‐
434              nal.
435
436              internal events can only be generated by the state  machine  it‐
437              self through the transition action next_event.
438
439       external_event_type() = {call, From :: from()} | cast | info
440
441              External events are of 3 types: {call,From}, cast, or info. Type
442              call originates from  the  API  functions  call/2  and  send_re‐
443              quest/2.  For  calls,  the event contains whom to reply to. Type
444              cast originates from the API function cast/2. Type  info  origi‐
445              nates from regular process messages sent to the gen_statem.
446
447       timeout_event_type() =
448           timeout | {timeout, Name :: term()} | state_timeout
449
450              There  are 3 types of time-out events that the state machine can
451              generate for itself with the corresponding timeout_action()s.
452
453       callback_mode_result() =
454           callback_mode() | [callback_mode() | state_enter()]
455
456              This is the return type from Module:callback_mode/0 and  selects
457              callback mode and whether to do state enter calls, or not.
458
459       callback_mode() = state_functions | handle_event_function
460
461              The  callback  mode  is selected with the return value from Mod‐
462              ule:callback_mode/0:
463
464                state_functions:
465                  The state must be of  type  state_name()  and  one  callback
466                  function per state, that is, Module:StateName/3, is used.
467
468                handle_event_function:
469                  The  state  can  be  any term and the callback function Mod‐
470                  ule:handle_event/4 is used for all states.
471
472              The function Module:callback_mode/0 is called when starting  the
473              gen_statem,  after  code  change and after changing the callback
474              module  with  any   of   the   actions   change_callback_module,
475              push_callback_module   or  pop_callback_module.  The  result  is
476              cached for subsequent calls to state callbacks.
477
478       state_enter() = state_enter
479
480              Whether the state machine should use state enter calls or not is
481              selected  when starting the gen_statem and after code change us‐
482              ing the return value from Module:callback_mode/0.
483
484              If Module:callback_mode/0 returns a list containing state_enter,
485              the  gen_statem  engine  will,  at  every state change, call the
486              state callback with arguments (enter, OldState, Data) or (enter,
487              OldState, State, Data), depending on the callback mode. This may
488              look like an event but is really a call performed after the pre‐
489              vious  state callback returned and before any event is delivered
490              to the new  state  callback.  See  Module:StateName/3  and  Mod‐
491              ule:handle_event/4.  Such  a call can be repeated by returning a
492              repeat_state or repeat_state_and_data tuple from the state call‐
493              back.
494
495              If  Module:callback_mode/0 does not return such a list, no state
496              enter calls are done.
497
498              If Module:code_change/4 should transform the state,  it  is  re‐
499              garded  as a state rename and not a state change, which will not
500              cause a state enter call.
501
502              Note that a state enter call will be done right before  entering
503              the  initial  state  even  though  this  actually is not a state
504              change. In this case OldState =:= State, which cannot happen for
505              a  subsequent  state  change, but will happen when repeating the
506              state enter call.
507
508       transition_option() =
509           postpone() |
510           hibernate() |
511           event_timeout() |
512           generic_timeout() |
513           state_timeout()
514
515              Transition options can be set by actions and  modify  the  state
516              transition.  The  state  transition  takes  place when the state
517              callback has processed an event and returns. Here  are  the  se‐
518              quence of steps for a state transition:
519
520                * All  returned  actions are processed in order of appearance.
521                  In this step all replies generated by any reply_action() are
522                  sent.  Other actions set transition_option()s that come into
523                  play in subsequent steps.
524
525                * If state enter calls are used, and either it is the  initial
526                  state  or  one of the callback results repeat_state_and_data
527                  or repeat_state_and_data is used the gen_statem engine calls
528                  the  current  state  callback  with arguments (enter, State,
529                  Data) or (enter, State, State, Data) (depending on  callback
530                  mode)  and when it returns starts again from the top of this
531                  sequence.
532
533                  If state enter calls are used, and  the  state  changes  the
534                  gen_statem  engine  calls  the new state callback with argu‐
535                  ments (enter, OldState, Data) or  (enter,  OldState,  State,
536                  Data)  (depending  on  callback  mode)  and  when it returns
537                  starts again from the top of this sequence.
538
539                * If postpone() is true, the current event is postponed.
540
541                * If this is a state change, the queue of incoming  events  is
542                  reset to start with the oldest postponed.
543
544                * All  events  stored with action() next_event are inserted to
545                  be processed before previously queued events.
546
547                * Time-out  timers  event_timeout(),   generic_timeout()   and
548                  state_timeout()  are  handled.  Time-outs with zero time are
549                  guaranteed to be delivered to the state machine  before  any
550                  external  not yet received event so if there is such a time-
551                  out requested, the corresponding time-out zero event is  en‐
552                  queued  as  the newest received event; that is after already
553                  queued events such as inserted and postponed events.
554
555                  Any event cancels an event_timeout() so a  zero  time  event
556                  time-out is only generated if the event queue is empty.
557
558                  A state change cancels a state_timeout() and any new transi‐
559                  tion option of this type belongs to the new state, that  is;
560                  a state_timeout() applies to the state the state machine en‐
561                  ters.
562
563                * If there are enqueued events the state callback for the pos‐
564                  sibly  new  state  is called with the oldest enqueued event,
565                  and we start again from the top of this sequence.
566
567                * Otherwise the gen_statem goes into  receive  or  hibernation
568                  (if  hibernate()  is  true) to wait for the next message. In
569                  hibernation  the   next   non-system   event   awakens   the
570                  gen_statem,  or rather the next incoming message awakens the
571                  gen_statem, but if it is a system event it goes  right  back
572                  into hibernation. When a new message arrives the state call‐
573                  back is called with the corresponding event,  and  we  start
574                  again from the top of this sequence.
575
576       postpone() = boolean()
577
578              If  true,  postpones  the  current  event and retries it after a
579              state change (NextState =/= State).
580
581       hibernate() = boolean()
582
583              If true, hibernates the gen_statem  by  calling  proc_lib:hiber‐
584              nate/3  before  going  into  receive  to wait for a new external
585              event.
586
587          Note:
588              If there are enqueued events to process when hibrnation  is  re‐
589              quested,  this is optimized by not hibernating but instead call‐
590              ing erlang:garbage_collect/0 to simulate that the gen_statem en‐
591              tered  hibernation  and  immediately got awakened by an enqueued
592              event.
593
594
595       event_timeout() = timeout() | integer()
596
597              Starts a timer set by enter_action() timeout. When the timer ex‐
598              pires  an  event  of event_type() timeout will be generated. See
599              erlang:start_timer/4 for how Time and Options  are  interpreted.
600              Future erlang:start_timer/4 Options will not necessarily be sup‐
601              ported.
602
603              Any event that arrives cancels this time-out. Note  that  a  re‐
604              tried or inserted event counts as arrived. So does a state time-
605              out zero event, if it was generated before this time-out is  re‐
606              quested.
607
608              If  Time is infinity, no timer is started, as it never would ex‐
609              pire anyway.
610
611              If Time is relative and 0 no timer is actually started,  instead
612              the  the  time-out event is enqueued to ensure that it gets pro‐
613              cessed before any not yet received external event, but after al‐
614              ready queued events.
615
616              Note that it is not possible nor needed to cancel this time-out,
617              as it is cancelled automatically by any other event.
618
619       generic_timeout() = timeout() | integer()
620
621              Starts a timer set by enter_action()  {timeout,Name}.  When  the
622              timer  expires  an  event of event_type() {timeout,Name} will be
623              generated. See erlang:start_timer/4 for how Time and Options are
624              interpreted. Future erlang:start_timer/4 Options will not neces‐
625              sarily be supported.
626
627              If Time is infinity, no timer is started, as it never would  ex‐
628              pire anyway.
629
630              If  Time is relative and 0 no timer is actually started, instead
631              the the time-out event is enqueued to ensure that it  gets  pro‐
632              cessed before any not yet received external event.
633
634              Setting  a  timer  with  the  same Name while it is running will
635              restart it with the new time-out value. Therefore it is possible
636              to cancel a specific time-out by setting it to infinity.
637
638       state_timeout() = timeout() | integer()
639
640              Starts  a  timer  set  by enter_action() state_timeout. When the
641              timer expires an event of  event_type()  state_timeout  will  be
642              generated. See erlang:start_timer/4 for how Time and Options are
643              interpreted. Future erlang:start_timer/4 Options will not neces‐
644              sarily be supported.
645
646              If  Time is infinity, no timer is started, as it never would ex‐
647              pire anyway.
648
649              If Time is relative and 0 no timer is actually started,  instead
650              the  the  time-out event is enqueued to ensure that it gets pro‐
651              cessed before any not yet received external event.
652
653              Setting this timer while it is running will restart it with  the
654              new  time-out  value.  Therefore  it  is possible to cancel this
655              time-out by setting it to infinity.
656
657       timeout_option() = {abs, Abs :: boolean()}
658
659              If Abs is true an absolute timer is started, and if it is  false
660              a  relative,  which is the default. See erlang:start_timer/4 for
661              details.
662
663       action() =
664           postpone |
665           {postpone, Postpone :: postpone()} |
666           {next_event,
667            EventType :: event_type(),
668            EventContent :: term()} |
669           {change_callback_module, NewModule :: module()} |
670           {push_callback_module, NewModule :: module()} |
671           pop_callback_module |
672           enter_action()
673
674              These transition actions can be invoked by returning  them  from
675              the  state  callback  when it is called with an event, from Mod‐
676              ule:init/1 or by giving them to enter_loop/5,6.
677
678              Actions are executed in the containing list order.
679
680              Actions that set  transition options  override any  previous  of
681              the  same type, so the last in the containing list wins. For ex‐
682              ample, the last postpone() overrides any previous postpone()  in
683              the list.
684
685                postpone:
686                  Sets the transition_option() postpone() for this state tran‐
687                  sition. This action  is  ignored  when  returned  from  Mod‐
688                  ule:init/1  or given to enter_loop/5,6, as there is no event
689                  to postpone in those cases.
690
691                next_event:
692                  This action does not set any transition_option() but instead
693                  stores  the  specified EventType and EventContent for inser‐
694                  tion after all actions have been executed.
695
696                  The stored events are inserted in the queue as the  next  to
697                  process before any already queued events. The order of these
698                  stored events is preserved, so the first next_event  in  the
699                  containing list becomes the first to process.
700
701                  An event of type internal is to be used when you want to re‐
702                  liably distinguish an event inserted this way from  any  ex‐
703                  ternal event.
704
705                change_callback_module:
706                  Changes  the callback module to NewModule which will be used
707                  when calling all subsequent state callbacks.
708
709                  The gen_statem engine will find out  the  callback  mode  of
710                  NewModule  by  calling  NewModule:callback_mode/0 before the
711                  next state callback.
712
713                  Changing the callback module does not affect the state tran‐
714                  sition in any way, it only changes which module that handles
715                  the events. Be aware that all relevant callback functions in
716                  NewModule    such    as    the   state   callback,   NewMod‐
717                  ule:code_change/4,  NewModule:format_status/2  and   NewMod‐
718                  ule:terminate/3  must  be  able to handle the state and data
719                  from the old module.
720
721                push_callback_module:
722                  Pushes the current callback module to the top of an internal
723                  stack of callback modules and changes the callback module to
724                  NewModule. Otherwise like  {change_callback_module,  NewMod‐
725                  ule} above.
726
727                pop_callback_module:
728                   Pops  the  top  module  from the internal stack of callback
729                  modules and changes the callback module  to  be  the  popped
730                  module.  If  the  stack is empty the server fails. Otherwise
731                  like {change_callback_module, NewModule} above.
732
733       enter_action() =
734           hibernate |
735           {hibernate, Hibernate :: hibernate()} |
736           timeout_action() |
737           reply_action()
738
739              These transition actions can be invoked by returning  them  from
740              the  state callback, from Module:init/1 or by giving them to en‐
741              ter_loop/5,6.
742
743              Actions are executed in the containing list order.
744
745              Actions that set transition options override any previous of the
746              same type, so the last in the containing list wins. For example,
747              the last event_timeout() overrides any previous  event_timeout()
748              in the list.
749
750                hibernate:
751                  Sets  the  transition_option()  hibernate()  for  this state
752                  transition.
753
754       timeout_action() =
755           (Time :: event_timeout()) |
756           {timeout, Time :: event_timeout(), EventContent :: term()} |
757           {timeout,
758            Time :: event_timeout(),
759            EventContent :: term(),
760            Options :: timeout_option() | [timeout_option()]} |
761           {{timeout, Name :: term()},
762            Time :: generic_timeout(),
763            EventContent :: term()} |
764           {{timeout, Name :: term()},
765            Time :: generic_timeout(),
766            EventContent :: term(),
767            Options :: timeout_option() | [timeout_option()]} |
768           {state_timeout,
769            Time :: state_timeout(),
770            EventContent :: term()} |
771           {state_timeout,
772            Time :: state_timeout(),
773            EventContent :: term(),
774            Options :: timeout_option() | [timeout_option()]} |
775           timeout_cancel_action() |
776           timeout_update_action()
777
778              These transition actions can be invoked by returning  them  from
779              the  state callback, from Module:init/1 or by giving them to en‐
780              ter_loop/5,6.
781
782              These time-out actions sets time-out transition options.
783
784                Time:
785                  Short for {timeout,Time,Time}, that is, the time-out message
786                  is  the  time-out  time.  This form exists to make the state
787                  callback  return  value  {next_state,NextState,NewData,Time}
788                  allowed like for gen_fsm.
789
790                timeout:
791                  Sets  the  transition_option()  event_timeout() to Time with
792                  EventContent and time-out options Options.
793
794                {timeout,Name}:
795                  Sets the transition_option() generic_timeout() to  Time  for
796                  Name with EventContent and time-out options Options.
797
798                state_timeout:
799                  Sets  the  transition_option()  state_timeout() to Time with
800                  EventContent and time-out options Options.
801
802       timeout_cancel_action() =
803           {timeout, cancel} |
804           {{timeout, Name :: term()}, cancel} |
805           {state_timeout, cancel}
806
807              This is a shorter and clearer form  of   timeout_action()   with
808              Time = infinity which cancels a time-out.
809
810       timeout_update_action() =
811           {timeout, update, EventContent :: term()} |
812           {{timeout, Name :: term()}, update, EventContent :: term()} |
813           {state_timeout, update, EventContent :: term()}
814
815              Updates  a  time-out  with  a new EventContent. See  timeout_ac‐
816              tion()  for how to start a time-out.
817
818              If no time-out of the same type is  active  instead  insert  the
819              time-out  event just like when starting a time-out with relative
820              Time = 0.
821
822       reply_action() = {reply, From :: from(), Reply :: term()}
823
824              This transition action can be invoked by returning it  from  the
825              state  callback,  from  Module:init/1  or  by  giving  it to en‐
826              ter_loop/5,6.
827
828              It does not set any transition_option() but instead replies to a
829              caller waiting for a reply in call/2. From must be the term from
830              argument {call,From} in a call to a state callback.
831
832              Note that using this action from Module:init/1 or enter_loop/5,6
833              would  be weird on the border of witchcraft since there has been
834              no earlier call to a state callback in this server.
835
836       init_result(StateType) =
837           {ok, State :: StateType, Data :: data()} |
838           {ok,
839            State :: StateType,
840            Data :: data(),
841            Actions :: [action()] | action()} |
842           ignore |
843           {stop, Reason :: term()}
844
845              For a succesful initialization, State is the initial state() and
846              Data the initial server data() of the gen_statem.
847
848              The  Actions  are executed when entering the first state just as
849              for a state callback, except that the action postpone is  forced
850              to false since there is no event to postpone.
851
852              For  an  unsuccesful  initialization,  {stop,Reason}  or  ignore
853              should be used; see start_link/3,4.
854
855       state_enter_result(State) =
856           {next_state, State, NewData :: data()} |
857           {next_state, State,
858            NewData :: data(),
859            Actions :: [enter_action()] | enter_action()} |
860           state_callback_result(enter_action())
861
862              State is the current state and it cannot be  changed  since  the
863              state callback was called with a state enter call.
864
865                next_state:
866                  The  gen_statem  does a state transition to State, which has
867                  to be the current state, sets NewData, and executes all  Ac‐
868                  tions.
869
870       event_handler_result(StateType) =
871           {next_state, NextState :: StateType, NewData :: data()} |
872           {next_state,
873            NextState :: StateType,
874            NewData :: data(),
875            Actions :: [action()] | action()} |
876           state_callback_result(action())
877
878              StateType  is  state_name() if callback mode is state_functions,
879              or state() if callback mode is handle_event_function.
880
881                next_state:
882                  The gen_statem does a state transition to  NextState  (which
883                  can be the same as the current state), sets NewData, and ex‐
884                  ecutes all Actions. If NextState =/= CurrentState the  state
885                  transition is a state change.
886
887       state_callback_result(ActionType) =
888           {keep_state, NewData :: data()} |
889           {keep_state,
890            NewData :: data(),
891            Actions :: [ActionType] | ActionType} |
892           keep_state_and_data |
893           {keep_state_and_data, Actions :: [ActionType] | ActionType} |
894           {repeat_state, NewData :: data()} |
895           {repeat_state,
896            NewData :: data(),
897            Actions :: [ActionType] | ActionType} |
898           repeat_state_and_data |
899           {repeat_state_and_data, Actions :: [ActionType] | ActionType} |
900           stop |
901           {stop, Reason :: term()} |
902           {stop, Reason :: term(), NewData :: data()} |
903           {stop_and_reply,
904            Reason :: term(),
905            Replies :: [reply_action()] | reply_action()} |
906           {stop_and_reply,
907            Reason :: term(),
908            Replies :: [reply_action()] | reply_action(),
909            NewData :: data()}
910
911              ActionType  is  enter_action()  if the state callback was called
912              with a state enter call and action() if the state  callback  was
913              called with an event.
914
915                keep_state:
916                  The same as {next_state,CurrentState,NewData,Actions}.
917
918                keep_state_and_data:
919                  The same as {keep_state,CurrentData,Actions}.
920
921                repeat_state:
922                  If the gen_statem runs with state enter calls, the state en‐
923                  ter call is repeated, see  type  transition_option(),  other
924                  than that repeat_state is the same as keep_state.
925
926                repeat_state_and_data:
927                  The same as {repeat_state,CurrentData,Actions}.
928
929                stop:
930                  Terminates the gen_statem by calling Module:terminate/3 with
931                  Reason and NewData, if specified. An exit signal  with  this
932                  reason  is  sent  to linked processes and ports. The default
933                  Reason is normal.
934
935                stop_and_reply:
936                  Sends all Replies, then terminates the gen_statem by calling
937                  Module:terminate/3 with Reason and NewData, if specified. An
938                  exit signal with this reason is sent to linked processes and
939                  ports.
940
941              All  these terms are tuples or atoms and this property will hold
942              in any future version of gen_statem.
943
944       request_id() = term()
945
946              A request handle, see send_request/2 for details.
947

EXPORTS

949       call(ServerRef :: server_ref(), Request :: term()) ->
950               Reply :: term()
951
952       call(ServerRef :: server_ref(),
953            Request :: term(),
954            Timeout ::
955                timeout() |
956                {clean_timeout, T :: timeout()} |
957                {dirty_timeout, T :: timeout()}) ->
958               Reply :: term()
959
960              Makes a synchronous call to the gen_statem ServerRef by  sending
961              a  request  and  waiting until its reply arrives. The gen_statem
962              calls the state callback with event_type() {call,From} and event
963              content Request.
964
965              A  Reply  is  generated  when a state callback returns with {re‐
966              ply,From,Reply} as one action(), and that Reply becomes the  re‐
967              turn value of this function.
968
969              Timeout is an integer > 0, which specifies how many milliseconds
970              to wait for a reply, or the atom infinity to wait  indefinitely,
971              which  is the default. If no reply is received within the speci‐
972              fied time, the function call fails.
973
974          Note:
975              For Timeout < infinity, to avoid getting a  late  reply  in  the
976              caller's inbox if the caller should catch exceptions, this func‐
977              tion spawns a proxy process that does the  call.  A  late  reply
978              gets  delivered to the dead proxy process, hence gets discarded.
979              This is less efficient than using Timeout == infinity.
980
981
982              Timeout can also be a tuple  {clean_timeout,T}  or  {dirty_time‐
983              out,T},  where  T  is the time-out time. {clean_timeout,T} works
984              like just T described in the note above and uses a proxy process
985              while {dirty_timeout,T} bypasses the proxy process which is more
986              lightweight.
987
988          Note:
989              If you combine  catching  exceptions  from  this  function  with
990              {dirty_timeout,T}  to  avoid  that the calling process dies when
991              the call times out, you will have to be  prepared  to  handle  a
992              late reply. Note that there is an odd chance to get a late reply
993              even with {dirty_timeout,infinity} or infinity  for  example  in
994              the  event  of network problems. So why not just let the calling
995              process die by not catching the exception?
996
997
998              The call can also fail, for example, if the gen_statem dies  be‐
999              fore or during this function call.
1000
1001       cast(ServerRef :: server_ref(), Msg :: term()) -> ok
1002
1003              Sends  an asynchronous event to the gen_statem ServerRef and re‐
1004              turns ok  immediately,  ignoring  if  the  destination  node  or
1005              gen_statem  does not exist. The gen_statem calls the state call‐
1006              back with event_type() cast and event content Msg.
1007
1008       check_response(Msg :: term(), RequestId :: request_id()) ->
1009                         {reply, Reply :: term()} |
1010                         no_reply |
1011                         {error, {term(), server_ref()}}
1012
1013              This function is used to check if a previously received message,
1014              for  example  by  receive or handle_info/2, is a result of a re‐
1015              quest made with send_request/2. If Msg is a reply to the  handle
1016              RequestId the result of the request is returned in Reply. Other‐
1017              wise returns no_reply and no cleanup is done, and thus the func‐
1018              tion shall be invoked repeatedly until a reply is returned.
1019
1020              The  return  value  Reply is generated when a state callback re‐
1021              turns with {reply,From,Reply} as one action(),  and  that  Reply
1022              becomes the return value of this function.
1023
1024              The  function  returns an error if the gen_statem dies before or
1025              during this request.
1026
1027       enter_loop(Module :: module(),
1028                  Opts :: [enter_loop_opt()],
1029                  State :: state(),
1030                  Data :: data()) ->
1031                     no_return()
1032
1033              The same as enter_loop/6  with  Actions  =  []  except  that  no
1034              server_name()  must have been registered. This creates an anony‐
1035              mous server.
1036
1037       enter_loop(Module :: module(),
1038                  Opts :: [enter_loop_opt()],
1039                  State :: state(),
1040                  Data :: data(),
1041                  Server_or_Actions :: server_name() | pid() | [action()]) ->
1042                     no_return()
1043
1044              If Server_or_Actions is a list(), the same as  enter_loop/6  ex‐
1045              cept that no server_name() must have been registered and Actions
1046              = Server_or_Actions. This creates an anonymous server.
1047
1048              Otherwise the same as enter_loop/6 with Server  =  Server_or_Ac‐
1049              tions and Actions = [].
1050
1051       enter_loop(Module :: module(),
1052                  Opts :: [enter_loop_opt()],
1053                  State :: state(),
1054                  Data :: data(),
1055                  Server :: server_name() | pid(),
1056                  Actions :: [action()] | action()) ->
1057                     no_return()
1058
1059              Makes  the calling process become a gen_statem. Does not return,
1060              instead the calling process enters the gen_statem  receive  loop
1061              and  becomes  a  gen_statem  server.  The process must have been
1062              started using one of the start functions in proc_lib.  The  user
1063              is  responsible for any initialization of the process, including
1064              registering a name for it.
1065
1066              This function is useful when a more complex initialization  pro‐
1067              cedure is needed than the gen_statem behavior provides.
1068
1069              Module,   Opts   have   the   same   meaning   as  when  calling
1070              start[_link|_monitor]/3,4.
1071
1072              If Server is self() an anonymous server is created just as  when
1073              using  start[_link|_monitor]/3.  If  Server is a server_name() a
1074              named server is created just as  when  using  start[_link|_moni‐
1075              tor]/4.  However,  the  server_name() name must have been regis‐
1076              tered accordingly before this function is called.
1077
1078              State, Data, and Actions have the same meanings as in the return
1079              value  of Module:init/1. Also, the callback module does not need
1080              to export a Module:init/1 function.
1081
1082              The function fails if the calling process was not started  by  a
1083              proc_lib start function, or if it is not registered according to
1084              server_name().
1085
1086       receive_response(RequestId :: request_id()) ->
1087                           {reply, Reply :: term()} |
1088                           {error, {term(), server_ref()}}
1089
1090       receive_response(RequestId :: request_id(), Timeout :: timeout()) ->
1091                           {reply, Reply :: term()} |
1092                           timeout |
1093                           {error, {term(), server_ref()}}
1094
1095              This function is used to receive for a reply of a  request  made
1096              with  send_request/2  to  the  gen_statem process. This function
1097              must be called from the same process from  which  send_request/2
1098              was made.
1099
1100              Timeout  is an integer greater then or equal to zero that speci‐
1101              fies how many milliseconds to wait for an reply, or the atom in‐
1102              finity  to  wait indefinitely. Defaults to infinity. If no reply
1103              is received within the  specified  time,  the  function  returns
1104              timeout.  Assuming that the server executes on a node supporting
1105              aliases (introduced in OTP 24) no response will be received  af‐
1106              ter  a  timeout. Otherwise, a garbage response might be received
1107              at a later time.
1108
1109              The return value Reply is generated when a  state  callback  re‐
1110              turns  with  {reply,From,Reply}  as one action(), and that Reply
1111              becomes the return value of this function.
1112
1113              The function returns an error if the gen_statem dies  before  or
1114              during this function call.
1115
1116              The difference between wait_response() and receive_response() is
1117              that receive_response() abandons the request at timeout so  that
1118              a  potential  future  response is ignored, while wait_response()
1119              does not.
1120
1121       reply(Replies :: [reply_action()] | reply_action()) -> ok
1122
1123       reply(From :: from(), Reply :: term()) -> ok
1124
1125              This function can be used by a gen_statem to explicitly  send  a
1126              reply to a process that waits in call/2 when the reply cannot be
1127              defined in the return value of a state callback.
1128
1129              From must be the term from argument  {call,From}  to  the  state
1130              callback.  A reply or multiple replies canalso be sent using one
1131              or several reply_action()s from a state callback.
1132
1133          Note:
1134              A reply sent with this function is not visible in sys debug out‐
1135              put.
1136
1137
1138       send_request(ServerRef :: server_ref(), Request :: term()) ->
1139                       RequestId :: request_id()
1140
1141              Sends a request to the gen_statem ServerRef and returns a handle
1142              RequestId.
1143
1144              The return value RequestId shall later be used with  receive_re‐
1145              sponse/1,2,  wait_response/1,2, or check_response/2 to fetch the
1146              actual result of the request.
1147
1148              The      call       gen_statem:wait_response(gen_statem:send_re‐
1149              quest(ServerRef,Request),  Timeout) can be seen as equivalent to
1150              gen_statem:call(Server,Request,Timeout), ignoring the error han‐
1151              dling.
1152
1153              The  gen_statem  calls  the  state  callback  with  event_type()
1154              {call,From} and event content Request.
1155
1156              A Reply is generated when a state  callback  returns  with  {re‐
1157              ply,From,Reply}  as one action(), and that Reply becomes the re‐
1158              turn  value  of  receive_response/1,2,   wait_response/1,2,   or
1159              check_response/2 function.
1160
1161       start(Module :: module(), Args :: term(), Opts :: [start_opt()]) ->
1162                start_ret()
1163
1164       start(ServerName :: server_name(),
1165             Module :: module(),
1166             Args :: term(),
1167             Opts :: [start_opt()]) ->
1168                start_ret()
1169
1170              Creates  a standalone gen_statem process according to OTP design
1171              principles (using proc_lib  primitives).  As  it  does  not  get
1172              linked  to  the  calling  process, this start function cannot be
1173              used by a supervisor to start a child.
1174
1175              For  a  description  of  arguments  and   return   values,   see
1176              start_link/3,4.
1177
1178       start_link(Module :: module(),
1179                  Args :: term(),
1180                  Opts :: [start_opt()]) ->
1181                     start_ret()
1182
1183       start_link(ServerName :: server_name(),
1184                  Module :: module(),
1185                  Args :: term(),
1186                  Opts :: [start_opt()]) ->
1187                     start_ret()
1188
1189              Creates  a gen_statem process according to OTP design principles
1190              (using proc_lib  primitives)  that  is  linked  to  the  calling
1191              process. This is essential when the gen_statem must be part of a
1192              supervision tree so it gets linked to its supervisor.
1193
1194              The gen_statem process calls  Module:init/1  to  initialize  the
1195              server.    To   ensure   a   synchronized   startup   procedure,
1196              start_link/3,4 does not return until Module:init/1 has returned.
1197
1198              ServerName specifies  the  server_name()  to  register  for  the
1199              gen_statem.  If  the gen_statem is started with start_link/3, no
1200              ServerName is provided and the gen_statem is not registered.
1201
1202              Module is the name of the callback module.
1203
1204              Args is an arbitrary term that is passed as the argument to Mod‐
1205              ule:init/1.
1206
1207                * If  option {timeout,Time} is present in Opts, the gen_statem
1208                  is allowed to spend Time  milliseconds  initializing  or  it
1209                  terminates and the start function returns {error,timeout}.
1210
1211                * If    option    {hibernate_after,HibernateAfterTimeout}   is
1212                  present, the gen_statem process awaits any message  for  Hi‐
1213                  bernateAfterTimeout  milliseconds  and  if no message is re‐
1214                  ceived, the process goes into hibernation automatically  (by
1215                  calling proc_lib:hibernate/3).
1216
1217                * If option {debug,Dbgs} is present in Opts, debugging through
1218                  sys is activated.
1219
1220                * If  option  {spawn_opt,SpawnOpts}  is   present   in   Opts,
1221                  SpawnOpts  is  passed  as option list to erlang:spawn_opt/2,
1222                  which is used to spawn the gen_statem process.
1223
1224          Note:
1225              Using spawn option monitor is not allowed, it causes this  func‐
1226              tion to fail with reason badarg.
1227
1228
1229              If  the gen_statem is successfully created and initialized, this
1230              function returns  {ok,Pid},  where  Pid  is  the  pid()  of  the
1231              gen_statem.  If  a  process with the specified ServerName exists
1232              already, this  function  returns  {error,{already_started,Pid}},
1233              where Pid is the pid() of that process.
1234
1235              If  Module:init/1  fails with Reason, this function returns {er‐
1236              ror,Reason}. If Module:init/1 returns {stop,Reason}  or  ignore,
1237              the  process is terminated and this function returns {error,Rea‐
1238              son} or ignore, respectively. An exit signal with the same  Rea‐
1239              son (or normal if Module:init/1 returns ignore) is set to linked
1240              processes   and   ports,   including   the    process    calling
1241              start_link/3,4.
1242
1243       start_monitor(Module :: module(),
1244                     Args :: term(),
1245                     Opts :: [start_opt()]) ->
1246                        start_mon_ret()
1247
1248       start_monitor(ServerName :: server_name(),
1249                     Module :: module(),
1250                     Args :: term(),
1251                     Opts :: [start_opt()]) ->
1252                        start_mon_ret()
1253
1254              Creates  a standalone gen_statem process according to OTP design
1255              principles (using proc_lib primitives) and atomically sets up  a
1256              monitor  to the newly created process. As it does not get linked
1257              to the calling process, this start function cannot be used by  a
1258              supervisor to start a child.
1259
1260              For   a   description   of  arguments  and  return  values,  see
1261              start_link/3,4. Note that the return value on  successful  start
1262              differs   from  start_link/3,4.  start_monitor/3,4  will  return
1263              {ok,{Pid,Mon}} where  Pid  is  the  process  identifier  of  the
1264              process, and Mon is a reference to the monitor set up to monitor
1265              the process. If the start is not successful, the caller will  be
1266              blocked  until  the  DOWN  message has been received and removed
1267              from the message queue.
1268
1269       stop(ServerRef :: server_ref()) -> ok
1270
1271              The same as stop(ServerRef, normal, infinity).
1272
1273       stop(ServerRef :: server_ref(),
1274            Reason :: term(),
1275            Timeout :: timeout()) ->
1276               ok
1277
1278              Orders the gen_statem ServerRef to exit with the specified  Rea‐
1279              son  and  waits  for  it to terminate. The gen_statem calls Mod‐
1280              ule:terminate/3 before exiting.
1281
1282              This function returns ok if the server terminates with  the  ex‐
1283              pected reason. Any other reason than normal, shutdown, or {shut‐
1284              down,Term} causes an error report  to  be  issued  through  log‐
1285              ger(3).  An  exit  signal with the same reason is sent to linked
1286              processes and ports. The default Reason is normal.
1287
1288              Timeout is an integer > 0, which specifies how many milliseconds
1289              to  wait  for  the  server to terminate, or the atom infinity to
1290              wait indefinitely. Defaults to infinity. If the server does  not
1291              terminate  within  the  specified  time,  a timeout exception is
1292              raised.
1293
1294              If the process does not exist, a noproc exception is raised.
1295
1296       wait_response(RequestId :: request_id()) ->
1297                        {reply, Reply :: term()} |
1298                        {error, {term(), server_ref()}}
1299
1300       wait_response(RequestId :: request_id(), Timeout :: timeout()) ->
1301                        {reply, Reply :: term()} |
1302                        timeout |
1303                        {error, {term(), server_ref()}}
1304
1305              This function is used to wait for a reply of a request made with
1306              send_request/2  to the gen_statem process. This function must be
1307              called from the same process from which send_request/2 was made.
1308
1309              Timeout is an integer greater then or equal to zero that  speci‐
1310              fies how many milliseconds to wait for an reply, or the atom in‐
1311              finity to wait indefinitely. Defaults to infinity. If  no  reply
1312              is  received  within  the  specified  time, the function returns
1313              timeout and no cleanup is done, and thus the function can be in‐
1314              voked repeatedly until a reply is returned.
1315
1316              The  return  value  Reply is generated when a state callback re‐
1317              turns with {reply,From,Reply} as one action(),  and  that  Reply
1318              becomes the return value of this function.
1319
1320              The  function  returns an error if the gen_statem dies before or
1321              during this function call.
1322
1323              The difference between receive_response() and wait_response() is
1324              that  receive_response() abandons the request at timeout so that
1325              a potential future response is  ignored,  while  wait_response()
1326              does not.
1327

CALLBACK FUNCTIONS

1329       The  following  functions are to be exported from a gen_statem callback
1330       module.
1331

EXPORTS

1333       Module:callback_mode() -> CallbackMode
1334
1335              Types:
1336
1337                  CallbackMode  =  callback_mode()  |  [   callback_mode()   |
1338                 state_enter() ]
1339
1340              This  function  is  called by a gen_statem when it needs to find
1341              out the callback mode of  the  callback  module.  The  value  is
1342              cached by gen_statem for efficiency reasons, so this function is
1343              only called once after server start, after code change, and  af‐
1344              ter  changing  the  callback  module, but before the first state
1345              callback in  the  current  callback  module's  code  version  is
1346              called.  More  occasions  may  be  added  in  future versions of
1347              gen_statem.
1348
1349              Server start happens either when Module:init/1 returns  or  when
1350              enter_loop/4-6   is   called.  Code  change  happens  when  Mod‐
1351              ule:code_change/4 returns. A change of the callback module  hap‐
1352              pens   when   a  state  callback  returns  any  of  the  actions
1353              change_callback_module,   push_callback_module   or    pop_call‐
1354              back_module.
1355
1356              The  CallbackMode  is either just callback_mode() or a list con‐
1357              taining callback_mode() and possibly the atom state_enter.
1358
1359          Note:
1360              If this function's body does not return an inline constant value
1361              the callback module is doing something strange.
1362
1363
1364       Module:code_change(OldVsn, OldState, OldData, Extra) -> Result
1365
1366              Types:
1367
1368                 OldVsn = Vsn | {down,Vsn}
1369                  Vsn = term()
1370                 OldState = NewState = term()
1371                 Extra = term()
1372                 Result = {ok,NewState,NewData} | Reason
1373                  OldState = NewState = state()
1374                  OldData = NewData = data()
1375                 Reason = term()
1376
1377          Note:
1378              This  callback  is optional, so callback modules need not export
1379              it. If a release upgrade/downgrade with Change  =  {advanced,Ex‐
1380              tra}  specified in the .appup file is made when code_change/4 is
1381              not implemented the process will crash with exit reason undef.
1382
1383
1384              This function is called by a gen_statem when it is to update its
1385              internal state during a release upgrade/downgrade, that is, when
1386              the instruction {update,Module,Change,...}, where Change =  {ad‐
1387              vanced,Extra}, is specified in the appup file. For more informa‐
1388              tion, see OTP Design Principles.
1389
1390              For an upgrade, OldVsn is Vsn, and for a  downgrade,  OldVsn  is
1391              {down,Vsn}.  Vsn  is  defined by the vsn attribute(s) of the old
1392              version of the callback module Module. If no such  attribute  is
1393              defined, the version is the checksum of the Beam file.
1394
1395              OldState and OldData is the internal state of the gen_statem.
1396
1397              Extra  is  passed  "as is" from the {advanced,Extra} part of the
1398              update instruction.
1399
1400              If successful, the function must  return  the  updated  internal
1401              state in an {ok,NewState,NewData} tuple.
1402
1403              If  the  function  returns a failure Reason, the ongoing upgrade
1404              fails and rolls back to the old release. Note that Reason cannot
1405              be  an  {ok,_,_} tuple since that will be regarded as a {ok,New‐
1406              State,NewData} tuple, and that a tuple  matching  {ok,_}  is  an
1407              also invalid failure Reason. It is recommended to use an atom as
1408              Reason since it will be wrapped in an {error,Reason} tuple.
1409
1410              Also note when upgrading a gen_statem, this function  and  hence
1411              the Change = {advanced,Extra} parameter in the appup file is not
1412              only needed to update the internal state or to act on the  Extra
1413              argument.  It  is  also needed if an upgrade or downgrade should
1414              change callback mode, or else the callback mode after  the  code
1415              change  will  not  be  honoured,  most probably causing a server
1416              crash.
1417
1418              If the server changes callback module using any of  the  actions
1419              change_callback_module,    push_callback_module   or   pop_call‐
1420              back_module, be aware that it is  always  the  current  callback
1421              module  that will get this callback call. That the current call‐
1422              back module handles the current state and data update should  be
1423              no  surprise,  but  it  must be able to handle even parts of the
1424              state and data that it is not familiar with, somehow.
1425
1426              In the supervisor child specification there is a list of modules
1427              which  is recommended to contain only the callback module. For a
1428              gen_statem with multiple callback modules there is no real  need
1429              to  list all of them, it may not even be possible since the list
1430              could change after code upgrade. If this list would contain only
1431              the  start callback module, as recommended, what is important is
1432              to upgrade that module whenever a synchronized code  replacement
1433              is done. Then the release handler concludes that an upgrade that
1434              upgrades that module needs to suspend, code change,  and  resume
1435              any  server  whose child specification declares that it is using
1436              that module. And again; the current callback module will get the
1437              Module:code_change/4 call.
1438
1439       Module:init(Args) -> Result(StateType)
1440
1441              Types:
1442
1443                 Args = term()
1444                  Result(StateType) = init_result(StateType)
1445
1446              Whenever   a   gen_statem   is   started  using  start_link/3,4,
1447              start_monitor/3,4, or start/3,4, this function is called by  the
1448              new  process  to  initialize the implementation state and server
1449              data.
1450
1451              Args is the Args argument provided to that start function.
1452
1453          Note:
1454              Note that if the gen_statem is started through proc_lib and  en‐
1455              ter_loop/4-6,  this  callback  will  never be called. Since this
1456              callback is not optional it can in that case be implemented as:
1457
1458              -spec init(_) -> no_return().
1459              init(Args) -> erlang:error(not_implemented, [Args]).
1460
1461
1462       Module:format_status(Opt, [PDict,State,Data]) -> Status
1463
1464              Types:
1465
1466                 Opt = normal | terminate
1467                 PDict = [{Key, Value}]
1468                  State = state()
1469                  Data = data()
1470                 Key = term()
1471                 Value = term()
1472                 Status = term()
1473
1474          Note:
1475              This callback is optional, so a callback module does not need to
1476              export  it. The gen_statem module provides a default implementa‐
1477              tion of this function that returns {State,Data}.
1478
1479              If this callback is exported but fails, to hide possibly  sensi‐
1480              tive   data,   the   default   function   will   instead  return
1481              {State,Info}, where Info says nothing but  the  fact  that  for‐
1482              mat_status/2 has crashed.
1483
1484
1485              This  function is called by a gen_statem process when any of the
1486              following apply:
1487
1488                *
1489                   One of sys:get_status/1,2 is invoked to get the  gen_statem
1490                  status. Opt is set to the atom normal for this case.
1491
1492                *
1493                   The gen_statem terminates abnormally and logs an error. Opt
1494                  is set to the atom terminate for this case.
1495
1496              This function is useful for changing the form and appearance  of
1497              the gen_statem status for these cases. A callback module wishing
1498              to change the sys:get_status/1,2 return value and how its status
1499              appears  in  termination  error logs exports an instance of for‐
1500              mat_status/2, which returns a term describing the current status
1501              of the gen_statem.
1502
1503              PDict  is  the  current  value  of the process dictionary of the
1504              gen_statem.
1505
1506              State is the internal state of the gen_statem.
1507
1508              Data is the internal server data of the gen_statem.
1509
1510              The function is to return Status, a term that contains  the  ap‐
1511              propriate  details  of  the  current  state  and  status  of the
1512              gen_statem. There are no restrictions on  the  form  Status  can
1513              take,  but for the sys:get_status/1,2 case (when Opt is normal),
1514              the recommended form for the Status value is [{data,  [{"State",
1515              Term}]}], where Term provides relevant details of the gen_statem
1516              state. Following this recommendation is  not  required,  but  it
1517              makes the callback module status consistent with the rest of the
1518              sys:get_status/1,2 return value.
1519
1520              One use for this function is to return compact alternative state
1521              representations to avoid having large state terms printed in log
1522              files. Another use is to hide sensitive data from being  written
1523              to the error log.
1524
1525       Module:StateName(enter, OldState, Data) -> StateEnterResult(StateName)
1526       Module:StateName(EventType, EventContent, Data) -> StateFunctionResult
1527       Module:handle_event(enter,  OldState,  State,  Data)  ->  StateEnterRe‐
1528       sult(State)
1529       Module:handle_event(EventType,  EventContent,  State,  Data)  ->   Han‐
1530       dleEventResult
1531
1532              Types:
1533
1534                  EventType = event_type()
1535                 EventContent = term()
1536                  State = state()
1537                  Data = NewData = data()
1538                  StateEnterResult(StateName) = state_enter_result(StateName)
1539                  StateFunctionResult = event_handler_result(state_name())
1540                  StateEnterResult(State) = state_enter_result(State)
1541                  HandleEventResult = event_handler_result(state())
1542
1543              Whenever  a gen_statem receives an event from call/2, cast/2, or
1544              as a normal process message, one of these functions  is  called.
1545              If  callback  mode  is  state_functions,  Module:StateName/3  is
1546              called,  and  if  it   is   handle_event_function,   Module:han‐
1547              dle_event/4 is called.
1548
1549              If  EventType  is {call,From}, the caller waits for a reply. The
1550              reply can be sent from this or from any other state callback  by
1551              returning  with {reply,From,Reply} in Actions, in Replies, or by
1552              calling reply(From, Reply).
1553
1554              If this function returns with a next state that does  not  match
1555              equal  (=/=)  to the current state, all postponed events are re‐
1556              tried in the next state.
1557
1558              The only difference between StateFunctionResult and  HandleEven‐
1559              tResult  is  that for StateFunctionResult the next state must be
1560              an atom, but for HandleEventResult there is  no  restriction  on
1561              the next state.
1562
1563              For  options  that  can  be  set and actions that can be done by
1564              gen_statem after returning from this function, see action().
1565
1566              When the gen_statem runs with state enter calls, these functions
1567              are also called with arguments (enter, OldState, ...) during ev‐
1568              ery state change. In this case there are  some  restrictions  on
1569              the  actions  that  may  be  returned: postpone() is not allowed
1570              since a state enter call is not an event so there is no event to
1571              postpone,  and {next_event,_,_} is not allowed since using state
1572              enter calls should not affect how events are consumed  and  pro‐
1573              duced. You may also not change states from this call. Should you
1574              return {next_state,NextState, ...} with NextState =/= State  the
1575              gen_statem crashes. Note that it is actually allowed to use {re‐
1576              peat_state, NewData, ...} although it makes little  sense  since
1577              you immediately will be called again with a new state enter call
1578              making this just a weird way of looping, and  there  are  better
1579              ways  to  loop  in Erlang. If you do not update NewData and have
1580              some  loop  termination  condition,   or   if   you   use   {re‐
1581              peat_state_and_data, _} or repeat_state_and_data you have an in‐
1582              finite  loop!  You  are   advised   to   use   {keep_state,...},
1583              {keep_state_and_data,_}  or  keep_state_and_data  since changing
1584              states from a state enter call is not possible anyway.
1585
1586              Note the fact that you can use throw to return the result, which
1587              can    be    useful.    For    example    to   bail   out   with
1588              throw(keep_state_and_data) from deep within  complex  code  that
1589              cannot  return  {next_state,State,Data} because State or Data is
1590              no longer in scope.
1591
1592       Module:terminate(Reason, State, Data) -> Ignored
1593
1594              Types:
1595
1596                 Reason = normal | shutdown | {shutdown,term()} | term()
1597                 State = state()
1598                 Data = data()
1599                 Ignored = term()
1600
1601          Note:
1602              This callback is optional, so callback modules need  not  export
1603              it.  The  gen_statem  module  provides  a default implementation
1604              without cleanup.
1605
1606
1607              This function is called by a gen_statem when it is about to ter‐
1608              minate.  It  is  to  be the opposite of Module:init/1 and do any
1609              necessary cleaning up. When it returns,  the  gen_statem  termi‐
1610              nates with Reason. The return value is ignored.
1611
1612              Reason  is  a term denoting the stop reason and State is the in‐
1613              ternal state of the gen_statem.
1614
1615              Reason depends on why the gen_statem is terminating.  If  it  is
1616              because  another  callback  function  has returned, a stop tuple
1617              {stop,Reason} in Actions, Reason has the value specified in that
1618              tuple.  If  it is because of a failure, Reason is the error rea‐
1619              son.
1620
1621              If the gen_statem is part of a supervision tree and  is  ordered
1622              by  its  supervisor  to  terminate, this function is called with
1623              Reason = shutdown if both the following conditions apply:
1624
1625                * The gen_statem has been set to trap exit signals.
1626
1627                * The shutdown strategy as defined in the  supervisor's  child
1628                  specification is an integer time-out value, not brutal_kill.
1629
1630              Even  if  the gen_statem is not part of a supervision tree, this
1631              function is called if it receives an  'EXIT'  message  from  its
1632              parent. Reason is the same as in the 'EXIT' message.
1633
1634              Otherwise, the gen_statem is immediately terminated.
1635
1636              Notice  that  for  any  other  reason  than normal, shutdown, or
1637              {shutdown,Term}, the gen_statem is assumed to terminate  because
1638              of an error and an error report is issued using logger(3).
1639
1640              When  the gen_statem process exits, an exit signal with the same
1641              reason is sent to linked processes and ports.
1642

SEE ALSO

1644       gen_event(3), gen_fsm(3),  gen_server(3),  proc_lib(3),  supervisor(3),
1645       sys(3).
1646
1647
1648
1649Ericsson AB                      stdlib 3.16.1                   gen_statem(3)
Impressum