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           {local, atom()} |
331           {global, GlobalName :: term()} |
332           {via, RegMod :: module(), Name :: term()}
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: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 :: reply_tag()}
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       reply_tag()
408
409              A handle that associates a reply to the corresponding request.
410
411       state() = state_name() | term()
412
413              If the callback mode is handle_event_function, the state can  be
414              any  term. After a state change (NextState =/= State), all post‐
415              poned events are retried.
416
417       state_name() = atom()
418
419              If the callback mode is state_functions, the state  must  be  an
420              atom.  After a state change (NextState =/= State), all postponed
421              events are retried. Note that the state terminate is not  possi‐
422              ble  to  use  since  it would collide with the optional callback
423              function Module:terminate/3.
424
425       data() = term()
426
427              A term in which the state machine implementation is to store any
428              server  data  it  needs.  The  difference  between  this and the
429              state() itself is that a change in  this  data  does  not  cause
430              postponed  events to be retried. Hence, if a change in this data
431              would change the set of events that are handled, then that  data
432              item is to be made a part of the state.
433
434       event_type() =
435           external_event_type() | timeout_event_type() | internal
436
437              There  are 3 categories of events: external, timeout, and inter‐
438              nal.
439
440              internal events can only be generated by the state  machine  it‐
441              self through the transition action next_event.
442
443       external_event_type() = {call, From :: from()} | cast | info
444
445              External events are of 3 types: {call,From}, cast, or info. Type
446              call originates from  the  API  functions  call/2  and  send_re‐
447              quest/2.  For  calls,  the event contains whom to reply to. Type
448              cast originates from the API function cast/2. Type  info  origi‐
449              nates from regular process messages sent to the gen_statem.
450
451       timeout_event_type() =
452           timeout | {timeout, Name :: term()} | state_timeout
453
454              There  are 3 types of time-out events that the state machine can
455              generate for itself with the corresponding timeout_action()s.
456
457       event_content() = term()
458
459              Any event's content can be any term.
460
461              See event_type that describes the origins of the different event
462              types, which is also where the event content comes from.
463
464       callback_mode_result() =
465           callback_mode() | [callback_mode() | state_enter()]
466
467              This  is the return type from Module:callback_mode/0 and selects
468              callback mode and whether to do state enter calls, or not.
469
470       callback_mode() = state_functions | handle_event_function
471
472              The callback mode is selected with the return  value  from  Mod‐
473              ule:callback_mode/0:
474
475                state_functions:
476                  The  state  must  be  of  type state_name() and one callback
477                  function per state, that is, Module:StateName/3, is used.
478
479                handle_event_function:
480                  The state can be any term and  the  callback  function  Mod‐
481                  ule:handle_event/4 is used for all states.
482
483              The  function Module:callback_mode/0 is called when starting the
484              gen_statem, after code change and after  changing  the  callback
485              module   with   any   of   the  actions  change_callback_module,
486              push_callback_module  or  pop_callback_module.  The  result   is
487              cached for subsequent calls to state callbacks.
488
489       state_enter() = state_enter
490
491              Whether the state machine should use state enter calls or not is
492              selected when starting the gen_statem and after code change  us‐
493              ing the return value from Module:callback_mode/0.
494
495              If Module:callback_mode/0 returns a list containing state_enter,
496              the gen_statem engine will, at  every  state  change,  call  the
497              state callback with arguments (enter, OldState, Data) or (enter,
498              OldState, State, Data), depending on the callback mode. This may
499              look like an event but is really a call performed after the pre‐
500              vious state callback returned and before any event is  delivered
501              to  the  new  state  callback.  See  Module:StateName/3 and Mod‐
502              ule:handle_event/4. Such a call can be repeated by  returning  a
503              repeat_state or repeat_state_and_data tuple from the state call‐
504              back.
505
506              If Module:callback_mode/0 does not return such a list, no  state
507              enter calls are done.
508
509              If  Module:code_change/4  should  transform the state, it is re‐
510              garded as a state rename and not a state change, which will  not
511              cause a state enter call.
512
513              Note  that a state enter call will be done right before entering
514              the initial state even though  this  actually  is  not  a  state
515              change. In this case OldState =:= State, which cannot happen for
516              a subsequent state change, but will happen  when  repeating  the
517              state enter call.
518
519       transition_option() =
520           postpone() |
521           hibernate() |
522           event_timeout() |
523           generic_timeout() |
524           state_timeout()
525
526              Transition  options  can  be set by actions and modify the state
527              transition. The state transition  takes  place  when  the  state
528              callback  has  processed  an event and returns. Here are the se‐
529              quence of steps for a state transition:
530
531                * All returned actions are processed in order  of  appearance.
532                  In this step all replies generated by any reply_action() are
533                  sent. Other actions set transition_option()s that come  into
534                  play in subsequent steps.
535
536                * If  state enter calls are used, and either it is the initial
537                  state or one of the callback  results  repeat_state_and_data
538                  or repeat_state_and_data is used the gen_statem engine calls
539                  the current state callback  with  arguments  (enter,  State,
540                  Data)  or (enter, State, State, Data) (depending on callback
541                  mode) and when it returns starts again from the top of  this
542                  sequence.
543
544                  If  state  enter  calls  are used, and the state changes the
545                  gen_statem engine calls the new state  callback  with  argu‐
546                  ments  (enter,  OldState,  Data) or (enter, OldState, State,
547                  Data) (depending on  callback  mode)  and  when  it  returns
548                  starts again from the top of this sequence.
549
550                * If postpone() is true, the current event is postponed.
551
552                * If  this  is a state change, the queue of incoming events is
553                  reset to start with the oldest postponed.
554
555                * All events stored with action() next_event are  inserted  to
556                  be processed before previously queued events.
557
558                * Time-out   timers   event_timeout(),  generic_timeout()  and
559                  state_timeout() are handled. Time-outs with  zero  time  are
560                  guaranteed  to  be delivered to the state machine before any
561                  external not yet received event so if there is such a  time-
562                  out  requested, the corresponding time-out zero event is en‐
563                  queued as the newest received event; that is  after  already
564                  queued events such as inserted and postponed events.
565
566                  Any  event  cancels  an event_timeout() so a zero time event
567                  time-out is only generated if the event queue is empty.
568
569                  A state change cancels a state_timeout() and any new transi‐
570                  tion  option of this type belongs to the new state, that is;
571                  a state_timeout() applies to the state the state machine en‐
572                  ters.
573
574                * If there are enqueued events the state callback for the pos‐
575                  sibly new state is called with the  oldest  enqueued  event,
576                  and we start again from the top of this sequence.
577
578                * Otherwise  the  gen_statem  goes into receive or hibernation
579                  (if hibernate() is true) to wait for the  next  message.  In
580                  hibernation   the   next   non-system   event   awakens  the
581                  gen_statem, or rather the next incoming message awakens  the
582                  gen_statem,  but  if it is a system event it goes right back
583                  into hibernation. When a new message arrives the state call‐
584                  back  is  called  with the corresponding event, and we start
585                  again from the top of this sequence.
586
587       postpone() = boolean()
588
589              If true, postpones the current event  and  retries  it  after  a
590              state change (NextState =/= State).
591
592       hibernate() = boolean()
593
594              If  true,  hibernates  the gen_statem by calling proc_lib:hiber‐
595              nate/3 before going into receive to  wait  for  a  new  external
596              event.
597
598          Note:
599              If  there  are enqueued events to process when hibrnation is re‐
600              quested, this is optimized by not hibernating but instead  call‐
601              ing erlang:garbage_collect/0 to simulate that the gen_statem en‐
602              tered hibernation and immediately got awakened  by  an  enqueued
603              event.
604
605
606       event_timeout() = timeout() | integer()
607
608              Starts a timer set by enter_action() timeout. When the timer ex‐
609              pires an event of event_type() timeout will  be  generated.  See
610              erlang:start_timer/4  for  how Time and Options are interpreted.
611              Future erlang:start_timer/4 Options will not necessarily be sup‐
612              ported.
613
614              Any  event  that  arrives cancels this time-out. Note that a re‐
615              tried or inserted event counts as arrived. So does a state time-
616              out  zero event, if it was generated before this time-out is re‐
617              quested.
618
619              If Time is infinity, no timer is started, as it never would  ex‐
620              pire anyway.
621
622              If  Time is relative and 0 no timer is actually started, instead
623              the the time-out event is enqueued to ensure that it  gets  pro‐
624              cessed before any not yet received external event, but after al‐
625              ready queued events.
626
627              Note that it is not possible nor needed to cancel this time-out,
628              as it is cancelled automatically by any other event.
629
630       generic_timeout() = timeout() | integer()
631
632              Starts  a  timer  set by enter_action() {timeout,Name}. When the
633              timer expires an event of event_type()  {timeout,Name}  will  be
634              generated. See erlang:start_timer/4 for how Time and Options are
635              interpreted. Future erlang:start_timer/4 Options will not neces‐
636              sarily be supported.
637
638              If  Time is infinity, no timer is started, as it never would ex‐
639              pire anyway.
640
641              If Time is relative and 0 no timer is actually started,  instead
642              the  the  time-out event is enqueued to ensure that it gets pro‐
643              cessed before any not yet received external event.
644
645              Setting a timer with the same Name  while  it  is  running  will
646              restart it with the new time-out value. Therefore it is possible
647              to cancel a specific time-out by setting it to infinity.
648
649       state_timeout() = timeout() | integer()
650
651              Starts a timer set by  enter_action()  state_timeout.  When  the
652              timer  expires  an  event  of event_type() state_timeout will be
653              generated. See erlang:start_timer/4 for how Time and Options are
654              interpreted. Future erlang:start_timer/4 Options will not neces‐
655              sarily be supported.
656
657              If Time is infinity, no timer is started, as it never would  ex‐
658              pire anyway.
659
660              If  Time is relative and 0 no timer is actually started, instead
661              the the time-out event is enqueued to ensure that it  gets  pro‐
662              cessed before any not yet received external event.
663
664              Setting  this timer while it is running will restart it with the
665              new time-out value. Therefore it  is  possible  to  cancel  this
666              time-out by setting it to infinity.
667
668       timeout_option() = {abs, Abs :: boolean()}
669
670              If  Abs is true an absolute timer is started, and if it is false
671              a relative, which is the default. See  erlang:start_timer/4  for
672              details.
673
674       action() =
675           postpone |
676           {postpone, Postpone :: postpone()} |
677           {next_event,
678            EventType :: event_type(),
679            EventContent :: event_content()} |
680           {change_callback_module, NewModule :: module()} |
681           {push_callback_module, NewModule :: module()} |
682           pop_callback_module |
683           enter_action()
684
685              These  transition  actions can be invoked by returning them from
686              the state callback when it is called with an  event,  from  Mod‐
687              ule:init/1 or by giving them to enter_loop/5,6.
688
689              Actions are executed in the containing list order.
690
691              Actions  that  set  transition options  override any previous of
692              the same type, so the last in the containing list wins. For  ex‐
693              ample,  the last postpone() overrides any previous postpone() in
694              the list.
695
696                postpone:
697                  Sets the transition_option() postpone() for this state tran‐
698                  sition.  This  action  is  ignored  when  returned from Mod‐
699                  ule:init/1 or given to enter_loop/5,6, as there is no  event
700                  to postpone in those cases.
701
702                next_event:
703                  This action does not set any transition_option() but instead
704                  stores the specified EventType and EventContent  for  inser‐
705                  tion after all actions have been executed.
706
707                  The  stored  events are inserted in the queue as the next to
708                  process before any already queued events. The order of these
709                  stored  events  is preserved, so the first next_event in the
710                  containing list becomes the first to process.
711
712                  An event of type internal is to be used when you want to re‐
713                  liably  distinguish  an event inserted this way from any ex‐
714                  ternal event.
715
716                change_callback_module:
717                  Changes the callback module to NewModule which will be  used
718                  when calling all subsequent state callbacks.
719
720                  The  gen_statem  engine  will  find out the callback mode of
721                  NewModule by calling  NewModule:callback_mode/0  before  the
722                  next state callback.
723
724                  Changing the callback module does not affect the state tran‐
725                  sition in any way, it only changes which module that handles
726                  the events. Be aware that all relevant callback functions in
727                  NewModule   such   as   the    state    callback,    NewMod‐
728                  ule:code_change/4,   NewModule:format_status/1  and  NewMod‐
729                  ule:terminate/3 must be able to handle the  state  and  data
730                  from the old module.
731
732                push_callback_module:
733                  Pushes the current callback module to the top of an internal
734                  stack of callback modules and changes the callback module to
735                  NewModule.  Otherwise  like {change_callback_module, NewMod‐
736                  ule} above.
737
738                pop_callback_module:
739                   Pops the top module from the  internal  stack  of  callback
740                  modules  and  changes  the  callback module to be the popped
741                  module. If the stack is empty the  server  fails.  Otherwise
742                  like {change_callback_module, NewModule} above.
743
744       enter_action() =
745           hibernate |
746           {hibernate, Hibernate :: hibernate()} |
747           timeout_action() |
748           reply_action()
749
750              These  transition  actions can be invoked by returning them from
751              the state callback, from Module:init/1 or by giving them to  en‐
752              ter_loop/5,6.
753
754              Actions are executed in the containing list order.
755
756              Actions that set transition options override any previous of the
757              same type, so the last in the containing list wins. For example,
758              the  last event_timeout() overrides any previous event_timeout()
759              in the list.
760
761                hibernate:
762                  Sets the  transition_option()  hibernate()  for  this  state
763                  transition.
764
765       timeout_action() =
766           (Time :: event_timeout()) |
767           {timeout,
768            Time :: event_timeout(),
769            EventContent :: event_content()} |
770           {timeout,
771            Time :: event_timeout(),
772            EventContent :: event_content(),
773            Options :: timeout_option() | [timeout_option()]} |
774           {{timeout, Name :: term()},
775            Time :: generic_timeout(),
776            EventContent :: event_content()} |
777           {{timeout, Name :: term()},
778            Time :: generic_timeout(),
779            EventContent :: event_content(),
780            Options :: timeout_option() | [timeout_option()]} |
781           {state_timeout,
782            Time :: state_timeout(),
783            EventContent :: event_content()} |
784           {state_timeout,
785            Time :: state_timeout(),
786            EventContent :: event_content(),
787            Options :: timeout_option() | [timeout_option()]} |
788           timeout_cancel_action() |
789           timeout_update_action()
790
791              These  transition  actions can be invoked by returning them from
792              the state callback, from Module:init/1 or by giving them to  en‐
793              ter_loop/5,6.
794
795              These time-out actions sets time-out transition options.
796
797                Time:
798                  Short for {timeout,Time,Time}, that is, the time-out message
799                  is the time-out time. This form exists  to  make  the  state
800                  callback  return  value  {next_state,NextState,NewData,Time}
801                  allowed like for gen_fsm.
802
803                timeout:
804                  Sets the transition_option() event_timeout()  to  Time  with
805                  EventContent and time-out options Options.
806
807                {timeout,Name}:
808                  Sets  the  transition_option() generic_timeout() to Time for
809                  Name with EventContent and time-out options Options.
810
811                state_timeout:
812                  Sets the transition_option() state_timeout()  to  Time  with
813                  EventContent and time-out options Options.
814
815       timeout_cancel_action() =
816           {timeout, cancel} |
817           {{timeout, Name :: term()}, cancel} |
818           {state_timeout, cancel}
819
820              This  is  a  shorter and clearer form of  timeout_action()  with
821              Time = infinity which cancels a time-out.
822
823       timeout_update_action() =
824           {timeout, update, EventContent :: event_content()} |
825           {{timeout, Name :: term()},
826            update,
827            EventContent :: event_content()} |
828           {state_timeout, update, EventContent :: event_content()}
829
830              Updates a time-out with a  new  EventContent.  See   timeout_ac‐
831              tion()  for how to start a time-out.
832
833              If  no  time-out  of  the same type is active instead insert the
834              time-out event just like when starting a time-out with  relative
835              Time = 0.
836
837       reply_action() = {reply, From :: from(), Reply :: term()}
838
839              This  transition  action can be invoked by returning it from the
840              state callback, from  Module:init/1  or  by  giving  it  to  en‐
841              ter_loop/5,6.
842
843              It does not set any transition_option() but instead replies to a
844              caller waiting for a reply in call/2. From must be the term from
845              argument {call,From} in a call to a state callback.
846
847              Note that using this action from Module:init/1 or enter_loop/5,6
848              would be weird on the border of witchcraft since there has  been
849              no earlier call to a state callback in this server.
850
851       init_result(StateType) = init_result(StateType, term())
852
853       init_result(StateType, DataType) =
854           {ok, State :: StateType, Data :: DataType} |
855           {ok,
856            State :: StateType,
857            Data :: DataType,
858            Actions :: [action()] | action()} |
859           ignore |
860           {stop, Reason :: term()}
861
862              For a succesful initialization, State is the initial state() and
863              Data the initial server data() of the gen_statem.
864
865              The Actions are executed when entering the first state  just  as
866              for  a state callback, except that the action postpone is forced
867              to false since there is no event to postpone.
868
869              For  an  unsuccesful  initialization,  {stop,Reason}  or  ignore
870              should be used; see start_link/3,4.
871
872       state_enter_result(State) = state_enter_result(State, term())
873
874       state_enter_result(State, DataType) =
875           {next_state, State, NewData :: DataType} |
876           {next_state, State,
877            NewData :: DataType,
878            Actions :: [enter_action()] | enter_action()} |
879           state_callback_result(enter_action())
880
881              State  is  the  current state and it cannot be changed since the
882              state callback was called with a state enter call.
883
884                next_state:
885                  The gen_statem does a state transition to State,  which  has
886                  to  be the current state, sets NewData, and executes all Ac‐
887                  tions.
888
889       event_handler_result(StateType) =
890           event_handler_result(StateType, term())
891
892       event_handler_result(StateType, DataType) =
893           {next_state, NextState :: StateType, NewData :: DataType} |
894           {next_state,
895            NextState :: StateType,
896            NewData :: DataType,
897            Actions :: [action()] | action()} |
898           state_callback_result(action())
899
900              StateType is state_name() if callback mode  is  state_functions,
901              or state() if callback mode is handle_event_function.
902
903                next_state:
904                  The  gen_statem  does a state transition to NextState (which
905                  can be the same as the current state), sets NewData, and ex‐
906                  ecutes  all Actions. If NextState =/= CurrentState the state
907                  transition is a state change.
908
909       state_callback_result(ActionType) =
910           state_callback_result(ActionType, term())
911
912       state_callback_result(ActionType, DataType) =
913           {keep_state, NewData :: DataType} |
914           {keep_state,
915            NewData :: DataType,
916            Actions :: [ActionType] | ActionType} |
917           keep_state_and_data |
918           {keep_state_and_data, Actions :: [ActionType] | ActionType} |
919           {repeat_state, NewData :: DataType} |
920           {repeat_state,
921            NewData :: DataType,
922            Actions :: [ActionType] | ActionType} |
923           repeat_state_and_data |
924           {repeat_state_and_data, Actions :: [ActionType] | ActionType} |
925           stop |
926           {stop, Reason :: term()} |
927           {stop, Reason :: term(), NewData :: DataType} |
928           {stop_and_reply,
929            Reason :: term(),
930            Replies :: [reply_action()] | reply_action()} |
931           {stop_and_reply,
932            Reason :: term(),
933            Replies :: [reply_action()] | reply_action(),
934            NewData :: DataType}
935
936              ActionType is enter_action() if the state  callback  was  called
937              with  a  state enter call and action() if the state callback was
938              called with an event.
939
940                keep_state:
941                  The same as {next_state,CurrentState,NewData,Actions}.
942
943                keep_state_and_data:
944                  The same as {keep_state,CurrentData,Actions}.
945
946                repeat_state:
947                  If the gen_statem runs with state enter calls, the state en‐
948                  ter  call  is  repeated, see type transition_option(), other
949                  than that repeat_state is the same as keep_state.
950
951                repeat_state_and_data:
952                  The same as {repeat_state,CurrentData,Actions}.
953
954                stop:
955                  Terminates the gen_statem by calling Module:terminate/3 with
956                  Reason  and  NewData, if specified. An exit signal with this
957                  reason is sent to linked processes and  ports.  The  default
958                  Reason is normal.
959
960                stop_and_reply:
961                  Sends all Replies, then terminates the gen_statem by calling
962                  Module:terminate/3 with Reason and NewData, if specified. An
963                  exit signal with this reason is sent to linked processes and
964                  ports.
965
966              All these terms are tuples or atoms and this property will  hold
967              in any future version of gen_statem.
968
969       request_id()
970
971              An opaque request identifier. See send_request/2 for details.
972
973       request_id_collection()
974
975              An opaque collection of request identifiers (request_id()) where
976              each request identifier can be associated with a label chosen by
977              the user. For more information see reqids_new/0.
978
979       response_timeout() = timeout() | {abs, integer()}
980
981              Used  to set a time limit on how long to wait for a response us‐
982              ing  either  receive_response/2,  receive_response/3,   wait_re‐
983              sponse/2, or wait_response/3. The time unit used is millisecond.
984              Currently valid values:
985
986                0..4294967295:
987                  Timeout relative to current time in milliseconds.
988
989                infinity:
990                  Infinite timeout. That is, the  operation  will  never  time
991                  out.
992
993                {abs, Timeout}:
994                  An  absolute  Erlang monotonic time timeout in milliseconds.
995                  That is, the  operation  will  time  out  when  erlang:mono‐
996                  tonic_time(millisecond) returns a value larger than or equal
997                  to Timeout. Timeout is not allowed to identify a  time  fur‐
998                  ther into the future than 4294967295 milliseconds. Identify‐
999                  ing the timeout using an absolute  timeout  value  is  espe‐
1000                  cially  handy  when you have a deadline for responses corre‐
1001                  sponding  to  a  complete  collection   of   requests   (re‐
1002                  quest_id_collection())  ,  since you do not have to recalcu‐
1003                  late the relative time until  the  deadline  over  and  over
1004                  again.
1005
1006       format_status() =
1007           #{state => state(),
1008             data => data(),
1009             reason => term(),
1010             queue => [{event_type(), event_content()}],
1011             postponed => [{event_type(), event_content()}],
1012             timeouts => [{timeout_event_type(), event_content()}],
1013             log => [sys:system_event()]}
1014
1015              A map that describes the gen_statem status. The keys are:
1016
1017                state:
1018                  The current state of the gen_statem process.
1019
1020                data:
1021                  The state data of the the gen_statem process.
1022
1023                reason:
1024                  The reason that caused the state machine to terminate.
1025
1026                queue:
1027                  The event queue of the gen_statem process.
1028
1029                postponed:
1030                   The postponed events queue of the gen_statem process.
1031
1032                timeouts:
1033                   The active time-outs of the gen_statem process.
1034
1035                log:
1036                   The sys log of the server.
1037
1038              New  associations  may  be added to the status map without prior
1039              notice.
1040

EXPORTS

1042       call(ServerRef :: server_ref(), Request :: term()) ->
1043               Reply :: term()
1044
1045       call(ServerRef :: server_ref(),
1046            Request :: term(),
1047            Timeout ::
1048                timeout() |
1049                {clean_timeout, T :: timeout()} |
1050                {dirty_timeout, T :: timeout()}) ->
1051               Reply :: term()
1052
1053              Makes a synchronous call to the gen_statem ServerRef by  sending
1054              a  request  and  waiting until its reply arrives. The gen_statem
1055              calls the state callback with event_type() {call,From} and event
1056              content Request.
1057
1058              A  Reply  is  generated  when a state callback returns with {re‐
1059              ply,From,Reply} as one action(), and that Reply becomes the  re‐
1060              turn value of this function.
1061
1062              Timeout is an integer > 0, which specifies how many milliseconds
1063              to wait for a reply, or the atom infinity to wait  indefinitely,
1064              which  is the default. If no reply is received within the speci‐
1065              fied time, the function call fails.
1066
1067          Note:
1068              For Timeout < infinity, to avoid getting a  late  reply  in  the
1069              caller's inbox if the caller should catch exceptions, this func‐
1070              tion spawns a proxy process that does the  call.  A  late  reply
1071              gets  delivered to the dead proxy process, hence gets discarded.
1072              This is less efficient than using Timeout == infinity.
1073
1074
1075              Timeout can also be a tuple  {clean_timeout,T}  or  {dirty_time‐
1076              out,T},  where  T  is the time-out time. {clean_timeout,T} works
1077              like just T described in the note above and uses a proxy process
1078              while {dirty_timeout,T} bypasses the proxy process which is more
1079              lightweight.
1080
1081          Note:
1082              If you combine  catching  exceptions  from  this  function  with
1083              {dirty_timeout,T}  to  avoid  that the calling process dies when
1084              the call times out, you will have to be  prepared  to  handle  a
1085              late reply. Note that there is an odd chance to get a late reply
1086              even with {dirty_timeout,infinity} or infinity  for  example  in
1087              the  event  of network problems. So why not just let the calling
1088              process die by not catching the exception?
1089
1090
1091              The call can also fail, for example, if the gen_statem dies  be‐
1092              fore or during this function call.
1093
1094              When this call fails it exits the calling process. The exit term
1095              is  on  the   form   {Reason,   Location}   where   Location   =
1096              {gen_statem,call,ArgList}.  See gen_server:call/3 that has a de‐
1097              scription of relevant values for the Reason in the exit term.
1098
1099       cast(ServerRef :: server_ref(), Msg :: term()) -> ok
1100
1101              Sends an asynchronous event to the gen_statem ServerRef and  re‐
1102              turns  ok  immediately,  ignoring  if  the  destination  node or
1103              gen_statem does not exist. The gen_statem calls the state  call‐
1104              back with event_type() cast and event content Msg.
1105
1106       check_response(Msg, ReqId) -> Result
1107
1108              Types:
1109
1110                 Msg = term()
1111                 ReqId = request_id()
1112                 Response =
1113                     {reply, Reply :: term()} |
1114                     {error, {Reason :: term(), server_ref()}}
1115                 Result = Response | no_reply
1116
1117              Check  if Msg is a response corresponding to the request identi‐
1118              fier ReqId. The request must have been made  by  send_request/2.
1119              If  Msg is a reply to the handle ReqId the result of the request
1120              is returned in Reply. Otherwise returns no_reply and no  cleanup
1121              is done, and thus the function shall be invoked repeatedly until
1122              a reply is returned.
1123
1124              The return value Reply is generated when a  state  callback  re‐
1125              turns  with  {reply,From,Reply}  as one action(), and that Reply
1126              becomes the return value of this function.
1127
1128              The function returns an error if the gen_statem dies  before  or
1129              during this request.
1130
1131       check_response(Msg, ReqIdCollection, Delete) -> Result
1132
1133              Types:
1134
1135                 Msg = term()
1136                 ReqIdCollection = request_id_collection()
1137                 Delete = boolean()
1138                 Response =
1139                     {reply, Reply :: term()} |
1140                     {error, {Reason :: term(), server_ref()}}
1141                 Result =
1142                     {Response,
1143                      Label :: term(),
1144                      NewReqIdCollection :: request_id_collection()} |
1145                     no_request | no_reply
1146
1147              Check if Msg is a response corresponding to a request identifier
1148              saved in ReqIdCollection. All request identifiers  of  ReqIdCol‐
1149              lection  must  correspond  to requests that have been made using
1150              send_request/2 or send_request/4, and all request must have been
1151              made by the process calling this function.
1152
1153              The  Label  in the response equals the Label associated with the
1154              request identifier that the response corresponds to.  The  Label
1155              of a request identifier is associated when saving the request id
1156              in a request identifier collection, or when sending the  request
1157              using send_request/4.
1158
1159              Compared  to  check_response/2,  the  returned result associated
1160              with a specific request identifier or  an  exception  associated
1161              with a specific request identifier will be wrapped in a 3-tuple.
1162              The first element of this tuple equals the value that would have
1163              been produced by check_response/2, the second element equals the
1164              Label associated with the specific request identifier,  and  the
1165              third  element NewReqIdCollection is a possibly modified request
1166              identifier collection.
1167
1168              If ReqIdCollection is empty, the atom  no_request  will  be  re‐
1169              turned. If Msg does not correspond to any of the request identi‐
1170              fiers in ReqIdCollection, the atom no_reply is returned.
1171
1172              If Delete equals true, the association with Label will have been
1173              deleted  from  ReqIdCollection  in the resulting NewReqIdCollec‐
1174              tion. If Delete equals false, NewReqIdCollection will equal  Re‐
1175              qIdCollection. Note that deleting an association is not for free
1176              and that a collection containing already  handled  requests  can
1177              still  be  used  by  subsequent  calls  to check_response/3, re‐
1178              ceive_response/3, and wait_response/3. However, without deleting
1179              handled associations, the above calls will not be able to detect
1180              when there are no more outstanding requests to  handle,  so  you
1181              will have to keep track of this some other way than relying on a
1182              no_request return. Note that if you pass a collection only  con‐
1183              taining associations of already handled or abandoned requests to
1184              check_response/3, it will always return no_reply.
1185
1186       enter_loop(Module :: module(),
1187                  Opts :: [enter_loop_opt()],
1188                  State :: state(),
1189                  Data :: data()) ->
1190                     no_return()
1191
1192              The same as enter_loop/6  with  Actions  =  []  except  that  no
1193              server_name()  must have been registered. This creates an anony‐
1194              mous server.
1195
1196       enter_loop(Module :: module(),
1197                  Opts :: [enter_loop_opt()],
1198                  State :: state(),
1199                  Data :: data(),
1200                  Server_or_Actions :: server_name() | pid() | [action()]) ->
1201                     no_return()
1202
1203              If Server_or_Actions is a list(), the same as  enter_loop/6  ex‐
1204              cept that no server_name() must have been registered and Actions
1205              = Server_or_Actions. This creates an anonymous server.
1206
1207              Otherwise the same as enter_loop/6 with Server  =  Server_or_Ac‐
1208              tions and Actions = [].
1209
1210       enter_loop(Module :: module(),
1211                  Opts :: [enter_loop_opt()],
1212                  State :: state(),
1213                  Data :: data(),
1214                  Server :: server_name() | pid(),
1215                  Actions :: [action()] | action()) ->
1216                     no_return()
1217
1218              Makes  the calling process become a gen_statem. Does not return,
1219              instead the calling process enters the gen_statem  receive  loop
1220              and  becomes  a  gen_statem  server.  The process must have been
1221              started using one of the start functions in proc_lib.  The  user
1222              is  responsible for any initialization of the process, including
1223              registering a name for it.
1224
1225              This function is useful when a more complex initialization  pro‐
1226              cedure is needed than the gen_statem behavior provides.
1227
1228              Module,   Opts   have   the   same   meaning   as  when  calling
1229              start[_link|_monitor]/3,4.
1230
1231              If Server is self() an anonymous server is created just as  when
1232              using  start[_link|_monitor]/3.  If  Server is a server_name() a
1233              named server is created just as  when  using  start[_link|_moni‐
1234              tor]/4.  However,  the  server_name() name must have been regis‐
1235              tered accordingly before this function is called.
1236
1237              State, Data, and Actions have the same meanings as in the return
1238              value  of Module:init/1. Also, the callback module does not need
1239              to export a Module:init/1 function.
1240
1241              The function fails if the calling process was not started  by  a
1242              proc_lib start function, or if it is not registered according to
1243              server_name().
1244
1245       receive_response(ReqId) -> Result
1246
1247              Types:
1248
1249                 ReqId = request_id()
1250                 Response =
1251                     {reply, Reply :: term()} |
1252                     {error, {Reason :: term(), server_ref()}}
1253                 Result = Response | timeout
1254
1255              The same as  calling  gen_statem:receive_response(ReqId,  infin‐
1256              ity).
1257
1258       receive_response(ReqId, Timeout) -> Result
1259
1260              Types:
1261
1262                 ReqId = request_id()
1263                 Timeout = response_timeout()
1264                 Response =
1265                     {reply, Reply :: term()} |
1266                     {error, {Reason :: term(), server_ref()}}
1267                 Result = Response | timeout
1268
1269              Receive  a  response corresponding to the request identifier Re‐
1270              qId- The request must have been made by  send_request/2  to  the
1271              gen_statem  process.  This function must be called from the same
1272              process from which send_request/2 was made.
1273
1274              Timeout specifies how long to wait for a  response.  If  no  re‐
1275              sponse  is  received within the specified time, the function re‐
1276              turns timeout. Assuming that the server executes on a node  sup‐
1277              porting  aliases (introduced in OTP 24) the request will also be
1278              abandoned. That is, no response will be received after  a  time‐
1279              out.  Otherwise,  a  stray response might be received at a later
1280              time.
1281
1282              The return value Reply is generated when a  state  callback  re‐
1283              turns  with  {reply,From,Reply}  as one action(), and that Reply
1284              becomes the return value of this function.
1285
1286              The function returns an error if the gen_statem dies  before  or
1287              during this function call.
1288
1289              The difference between wait_response/2 and receive_response/2 is
1290              that receive_response/2 abandons the request at timeout so  that
1291              a  potential  future  response is ignored, while wait_response/2
1292              does not.
1293
1294       receive_response(ReqIdCollection, Timeout, Delete) -> Result
1295
1296              Types:
1297
1298                 ReqIdCollection = request_id_collection()
1299                 Timeout = response_timeout()
1300                 Delete = boolean()
1301                 Response =
1302                     {reply, Reply :: term()} |
1303                     {error, {Reason :: term(), server_ref()}}
1304                 Result =
1305                     {Response,
1306                      Label :: term(),
1307                      NewReqIdCollection :: request_id_collection()} |
1308                     no_request | timeout
1309
1310              Receive a response corresponding to a request  identifier  saved
1311              in  ReqIdCollection.  All request identifiers of ReqIdCollection
1312              must correspond to requests that have been made  using  send_re‐
1313              quest/2  or  send_request/4, and all request must have been made
1314              by the process calling this function.
1315
1316              The Label in the response equals the Label associated  with  the
1317              request  identifier  that the response corresponds to. The Label
1318              of a request identifier is associated when adding the request id
1319              in  a request identifier collection, or when sending the request
1320              using send_request/4.
1321
1322              Compared to receive_response/2, the returned  result  associated
1323              with a specific request identifier will be wrapped in a 3-tuple.
1324              The first element of this tuple equals the value that would have
1325              been  produced  by receive_response/2, the second element equals
1326              the Label associated with the specific request  identifier,  and
1327              the  third element NewReqIdCollection is a possibly modified re‐
1328              quest identifier collection.
1329
1330              If ReqIdCollection is empty, the atom  no_request  will  be  re‐
1331              turned.
1332
1333              Timeout  specifies  how  long  to wait for a response. If no re‐
1334              sponse is received within the specified time, the  function  re‐
1335              turns  timeout. Assuming that the server executes on a node sup‐
1336              porting aliases (introduced in OTP 24) all  requests  identified
1337              by ReqIdCollection will also be abandoned. That is, no responses
1338              will be received after a  timeout.  Otherwise,  stray  responses
1339              might be received at a later time.
1340
1341              The difference between receive_response/3 and wait_response/3 is
1342              that receive_response/3 abandons the requests at timeout so that
1343              potential  future  responses  are ignored, while wait_response/3
1344              does not.
1345
1346              If Delete equals true, the association with Label will have been
1347              deleted  from  ReqIdCollection  in the resulting NewReqIdCollec‐
1348              tion. If Delete equals false, NewReqIdCollection will equal  Re‐
1349              qIdCollection. Note that deleting an association is not for free
1350              and that a collection containing already  handled  requests  can
1351              still   be  used  by  subsequent  calls  to  receive_response/3,
1352              check_response/3, and wait_response/3. However, without deleting
1353              handled associations, the above calls will not be able to detect
1354              when there are no more outstanding requests to  handle,  so  you
1355              will have to keep track of this some other way than relying on a
1356              no_request return. Note that if you pass a collection only  con‐
1357              taining associations of already handled or abandoned requests to
1358              receive_response/3, it will always block until a timeout  deter‐
1359              mined by Timeout is triggered.
1360
1361       reply(Replies :: [reply_action()] | reply_action()) -> ok
1362
1363       reply(From :: from(), Reply :: term()) -> ok
1364
1365              This  function  can be used by a gen_statem to explicitly send a
1366              reply to a process that waits in call/2 when the reply cannot be
1367              defined in the return value of a state callback.
1368
1369              From  must  be  the  term from argument {call,From} to the state
1370              callback. A reply or multiple replies canalso be sent using  one
1371              or several reply_action()s from a state callback.
1372
1373          Note:
1374              A reply sent with this function is not visible in sys debug out‐
1375              put.
1376
1377
1378       reqids_add(ReqId :: request_id(),
1379                  Label :: term(),
1380                  ReqIdCollection :: request_id_collection()) ->
1381                     NewReqIdCollection :: request_id_collection()
1382
1383              Saves ReqId and associates a Label with the  request  identifier
1384              by  adding this information to ReqIdCollection and returning the
1385              resulting request identifier collection.
1386
1387       reqids_new() -> NewReqIdCollection :: request_id_collection()
1388
1389              Returns a new empty request  identifier  collection.  A  request
1390              identifier collection can be utilized in order the handle multi‐
1391              ple outstanding requests.
1392
1393              Request identifiers of requests made by  send_request/2  can  be
1394              saved  in  a  request  identifier collection using reqids_add/3.
1395              Such a collection of request identifiers can later  be  used  in
1396              order to get one response corresponding to a request in the col‐
1397              lection by passing the collection  as  argument  to  receive_re‐
1398              sponse/3, wait_response/3, or, check_response/3.
1399
1400              reqids_size/1  can  be  used  to determine the amount of request
1401              identifiers in a request identifier collection.
1402
1403       reqids_size(ReqIdCollection :: request_id_collection()) ->
1404                      integer() >= 0
1405
1406              Returns the amount of request identifiers saved in  ReqIdCollec‐
1407              tion.
1408
1409       reqids_to_list(ReqIdCollection :: request_id_collection()) ->
1410                         [{ReqId :: request_id(), Label :: term()}]
1411
1412              Returns a list of {ReqId, Label} tuples which corresponds to all
1413              request identifiers with their associated labels present in  the
1414              ReqIdCollection collection.
1415
1416       send_request(ServerRef :: server_ref(), Request :: term()) ->
1417                       ReqId :: request_id()
1418
1419              Sends  an  asynchronous  call  request Request to the gen_statem
1420              process identified by ServerRef and returns a request identifier
1421              ReqId.  The  return  value  ReqId  shall  later be used with re‐
1422              ceive_response/2, wait_response/2, or check_response/2 to  fetch
1423              the  actual  result  of the request. Besides passing the request
1424              identifier directly to these functions, it can also be saved  in
1425              a  request identifier collection using reqids_add/3. Such a col‐
1426              lection of request identifiers can later be used in order to get
1427              one  response  corresponding  to  a request in the collection by
1428              passing  the  collection  as  argument  to   receive_response/3,
1429              wait_response/3,  or  check_response/3. If you are about to save
1430              the request identifier in a request identifier  collection,  you
1431              may want to consider using send_request/4 instead.
1432
1433              The       call      gen_statem:wait_response(gen_statem:send_re‐
1434              quest(ServerRef,Request), Timeout) can be seen as equivalent  to
1435              gen_statem:call(Server,Request,Timeout), ignoring the error han‐
1436              dling.
1437
1438              The  gen_statem  calls  the  state  callback  with  event_type()
1439              {call,From} and event content Request.
1440
1441              A  Reply  is  generated  when a state callback returns with {re‐
1442              ply,From,Reply} as one action(), and that Reply becomes the  re‐
1443              turn   value   of  receive_response/1,2,  wait_response/1,2,  or
1444              check_response/2 function.
1445
1446       send_request(ServerRef :: server_ref(),
1447                    Request :: term(),
1448                    Label :: term(),
1449                    ReqIdCollection :: request_id_collection()) ->
1450                       NewReqIdCollection :: request_id_collection()
1451
1452              Sends an asynchronous call request  Request  to  the  gen_statem
1453              process  identified  by  ServerRef. The Label will be associated
1454              with the request identifier of the operation and  added  to  the
1455              returned  request  identifier collection NewReqIdCollection. The
1456              collection can later be used in order to get one response corre‐
1457              sponding  to  a request in the collection by passing the collec‐
1458              tion as argument  to  receive_response/3,  wait_response/3,  or,
1459              check_response/3.
1460
1461              The   same   as   calling  gen_statem:reqids_add(statem:send_re‐
1462              quest(ServerRef, Request), Label, ReqIdCollection), but  calling
1463              send_request/4 is slightly more efficient.
1464
1465       start(Module :: module(), Args :: term(), Opts :: [start_opt()]) ->
1466                start_ret()
1467
1468       start(ServerName :: server_name(),
1469             Module :: module(),
1470             Args :: term(),
1471             Opts :: [start_opt()]) ->
1472                start_ret()
1473
1474              Creates  a standalone gen_statem process according to OTP design
1475              principles (using proc_lib  primitives).  As  it  does  not  get
1476              linked  to  the  calling  process, this start function cannot be
1477              used by a supervisor to start a child.
1478
1479              For  a  description  of  arguments  and   return   values,   see
1480              start_link/3,4.
1481
1482       start_link(Module :: module(),
1483                  Args :: term(),
1484                  Opts :: [start_opt()]) ->
1485                     start_ret()
1486
1487       start_link(ServerName :: server_name(),
1488                  Module :: module(),
1489                  Args :: term(),
1490                  Opts :: [start_opt()]) ->
1491                     start_ret()
1492
1493              Creates  a gen_statem process according to OTP design principles
1494              (using proc_lib  primitives)  that  is  linked  to  the  calling
1495              process. This is essential when the gen_statem must be part of a
1496              supervision tree so it gets linked to its supervisor.
1497
1498              The gen_statem process calls  Module:init/1  to  initialize  the
1499              server.    To   ensure   a   synchronized   startup   procedure,
1500              start_link/3,4 does not return until Module:init/1 has returned.
1501
1502              ServerName specifies  the  server_name()  to  register  for  the
1503              gen_statem.  If  the gen_statem is started with start_link/3, no
1504              ServerName is provided and the gen_statem is not registered.
1505
1506              Module is the name of the callback module.
1507
1508              Args is an arbitrary term that is passed as the argument to Mod‐
1509              ule:init/1.
1510
1511                * If  option {timeout,Time} is present in Opts, the gen_statem
1512                  is allowed to spend Time  milliseconds  initializing  or  it
1513                  terminates and the start function returns {error,timeout}.
1514
1515                * If    option    {hibernate_after,HibernateAfterTimeout}   is
1516                  present, the gen_statem process awaits any message  for  Hi‐
1517                  bernateAfterTimeout  milliseconds  and  if no message is re‐
1518                  ceived, the process goes into hibernation automatically  (by
1519                  calling proc_lib:hibernate/3).
1520
1521                * If option {debug,Dbgs} is present in Opts, debugging through
1522                  sys is activated.
1523
1524                * If  option  {spawn_opt,SpawnOpts}  is   present   in   Opts,
1525                  SpawnOpts  is  passed  as option list to erlang:spawn_opt/2,
1526                  which is used to spawn the gen_statem process.
1527
1528          Note:
1529              Using spawn option monitor is not allowed, it causes this  func‐
1530              tion to fail with reason badarg.
1531
1532
1533              If  the gen_statem is successfully created and initialized, this
1534              function returns  {ok,Pid},  where  Pid  is  the  pid()  of  the
1535              gen_statem.  If  a  process with the specified ServerName exists
1536              already, this  function  returns  {error,{already_started,Pid}},
1537              where Pid is the pid() of that process.
1538
1539              If  Module:init/1  fails with Reason, this function returns {er‐
1540              ror,Reason}. If Module:init/1 returns {stop,Reason}  or  ignore,
1541              the  process is terminated and this function returns {error,Rea‐
1542              son} or ignore, respectively. An exit signal with the same  Rea‐
1543              son (or normal if Module:init/1 returns ignore) is set to linked
1544              processes   and   ports,   including   the    process    calling
1545              start_link/3,4.
1546
1547       start_monitor(Module :: module(),
1548                     Args :: term(),
1549                     Opts :: [start_opt()]) ->
1550                        start_mon_ret()
1551
1552       start_monitor(ServerName :: server_name(),
1553                     Module :: module(),
1554                     Args :: term(),
1555                     Opts :: [start_opt()]) ->
1556                        start_mon_ret()
1557
1558              Creates  a standalone gen_statem process according to OTP design
1559              principles (using proc_lib primitives) and atomically sets up  a
1560              monitor  to the newly created process. As it does not get linked
1561              to the calling process, this start function cannot be used by  a
1562              supervisor to start a child.
1563
1564              For   a   description   of  arguments  and  return  values,  see
1565              start_link/3,4. Note that the return value on  successful  start
1566              differs   from  start_link/3,4.  start_monitor/3,4  will  return
1567              {ok,{Pid,Mon}} where  Pid  is  the  process  identifier  of  the
1568              process, and Mon is a reference to the monitor set up to monitor
1569              the process. If the start is not successful, the caller will  be
1570              blocked  until  the  DOWN  message has been received and removed
1571              from the message queue.
1572
1573       stop(ServerRef :: server_ref()) -> ok
1574
1575              The same as stop(ServerRef, normal, infinity).
1576
1577       stop(ServerRef :: server_ref(),
1578            Reason :: term(),
1579            Timeout :: timeout()) ->
1580               ok
1581
1582              Orders the gen_statem ServerRef to exit with the specified  Rea‐
1583              son  and  waits  for  it to terminate. The gen_statem calls Mod‐
1584              ule:terminate/3 before exiting.
1585
1586              This function returns ok if the server terminates with  the  ex‐
1587              pected reason. Any other reason than normal, shutdown, or {shut‐
1588              down,Term} causes an error report  to  be  issued  through  log‐
1589              ger(3).  An  exit  signal with the same reason is sent to linked
1590              processes and ports. The default Reason is normal.
1591
1592              Timeout is an integer > 0, which specifies how many milliseconds
1593              to  wait  for  the  server to terminate, or the atom infinity to
1594              wait indefinitely. Defaults to infinity. If the server does  not
1595              terminate  within the specified time, the call exits the calling
1596              process with reason timeout.
1597
1598              If the process does  not  exist,  the  call  exits  the  calling
1599              process  with  reason noproc, and with reason {nodedown,Node} if
1600              the connection fails to the remote Node where the server runs.
1601
1602       wait_response(ReqId) -> Result
1603
1604              Types:
1605
1606                 ReqId = request_id()
1607                 Response =
1608                     {reply, Reply :: term()} |
1609                     {error, {Reason :: term(), server_ref()}}
1610                 Result = Response | timeout
1611
1612              The same as  calling  gen_statem:receive_response(ReqId,  infin‐
1613              ity).
1614
1615       wait_response(ReqId, WaitTime) -> Result
1616
1617              Types:
1618
1619                 ReqId = request_id()
1620                 WaitTime = response_timeout()
1621                 Response =
1622                     {reply, Reply :: term()} |
1623                     {error, {Reason :: term(), server_ref()}}
1624                 Result = Response | timeout
1625
1626              Wait  for a response corresponding to the request identifier Re‐
1627              qId. The request must have been made by  send_request/2  to  the
1628              gen_statem  process.  This function must be called from the same
1629              process from which send_request/2 was made.
1630
1631              WaitTime specifies how long to wait for a reply. If no reply  is
1632              received within the specified time, the function returns timeout
1633              and no cleanup is done, and thus the function can be invoked re‐
1634              peatedly until a reply is returned.
1635
1636              The  return  value  Reply is generated when a state callback re‐
1637              turns with {reply,From,Reply} as one action(),  and  that  Reply
1638              becomes the return value of this function.
1639
1640              The  function  returns an error if the gen_statem dies before or
1641              during this function call.
1642
1643              The difference between receive_response/2 and wait_response/2 is
1644              that  receive_response/2 abandons the request at timeout so that
1645              a potential future response is  ignored,  while  wait_response/2
1646              does not.
1647
1648       wait_response(ReqIdCollection, WaitTime, Delete) -> Result
1649
1650              Types:
1651
1652                 ReqIdCollection = request_id_collection()
1653                 WaitTime = response_timeout()
1654                 Delete = boolean()
1655                 Response =
1656                     {reply, Reply :: term()} |
1657                     {error, {Reason :: term(), server_ref()}}
1658                 Result =
1659                     {Response,
1660                      Label :: term(),
1661                      NewReqIdCollection :: request_id_collection()} |
1662                     no_request | timeout
1663
1664              Wait  for a response corresponding to a request identifier saved
1665              in ReqIdCollection. All request identifiers  of  ReqIdCollection
1666              must  correspond  to requests that have been made using send_re‐
1667              quest/2 or send_request/4, and all request must have  been  made
1668              by the process calling this function.
1669
1670              The  Label  in the response equals the Label associated with the
1671              request identifier that the response corresponds to.  The  Label
1672              of a request identifier is associated when saving the request id
1673              in a request identifier collection, or when sending the  request
1674              using send_request/4.
1675
1676              Compared to wait_response/2, the returned result associated with
1677              a specific request identifier or an exception associated with  a
1678              specific  request  identifier  will be wrapped in a 3-tuple. The
1679              first element of this tuple equals the  value  that  would  have
1680              been  produced by wait_response/2, the second element equals the
1681              Label associated with the specific request identifier,  and  the
1682              third  element NewReqIdCollection is a possibly modified request
1683              identifier collection.
1684
1685              If ReqIdCollection is empty, no_request will be returned. If  no
1686              response  is received before the WaitTime timeout has triggered,
1687              the atom timeout is returned. It is valid  to  continue  waiting
1688              for  a  response as many times as needed up until a response has
1689              been received and  completed  by  check_response(),  receive_re‐
1690              sponse(), or wait_response().
1691
1692              The difference between receive_response/3 and wait_response/3 is
1693              that receive_response/3 abandons requests at timeout so  that  a
1694              potential  future  responses  are ignored, while wait_response/3
1695              does not.
1696
1697              If Delete equals true, the association with Label will have been
1698              deleted  from  ReqIdCollection  in the resulting NewReqIdCollec‐
1699              tion. If Delete equals false, NewReqIdCollection will equal  Re‐
1700              qIdCollection. Note that deleting an association is not for free
1701              and that a collection containing already  handled  requests  can
1702              still  be used by subsequent calls to wait_response/3, check_re‐
1703              sponse/3, and receive_response/3. However, without deleting han‐
1704              dled  associations,  the  above calls will not be able to detect
1705              when there are no more outstanding requests to  handle,  so  you
1706              will have to keep track of this some other way than relying on a
1707              no_request return. Note that if you pass a collection only  con‐
1708              taining associations of already handled or abandoned requests to
1709              wait_response/3, it will always block until a timeout determined
1710              by WaitTime is triggered and then return no_reply.
1711

CALLBACK FUNCTIONS

1713       The  following  functions are to be exported from a gen_statem callback
1714       module.
1715

EXPORTS

1717       Module:callback_mode() -> CallbackMode
1718
1719              Types:
1720
1721                  CallbackMode  =  callback_mode()  |  [   callback_mode()   |
1722                 state_enter() ]
1723
1724              This  function  is  called by a gen_statem when it needs to find
1725              out the callback mode of  the  callback  module.  The  value  is
1726              cached by gen_statem for efficiency reasons, so this function is
1727              only called once after server start, after code change, and  af‐
1728              ter  changing  the  callback  module, but before the first state
1729              callback in  the  current  callback  module's  code  version  is
1730              called.  More  occasions  may  be  added  in  future versions of
1731              gen_statem.
1732
1733              Server start happens either when Module:init/1 returns  or  when
1734              enter_loop/4-6   is   called.  Code  change  happens  when  Mod‐
1735              ule:code_change/4 returns. A change of the callback module  hap‐
1736              pens   when   a  state  callback  returns  any  of  the  actions
1737              change_callback_module,   push_callback_module   or    pop_call‐
1738              back_module.
1739
1740              The  CallbackMode  is either just callback_mode() or a list con‐
1741              taining callback_mode() and possibly the atom state_enter.
1742
1743          Note:
1744              If this function's body does not return an inline constant value
1745              the callback module is doing something strange.
1746
1747
1748       Module:code_change(OldVsn, OldState, OldData, Extra) -> Result
1749
1750              Types:
1751
1752                 OldVsn = Vsn | {down,Vsn}
1753                  Vsn = term()
1754                 OldState = NewState = term()
1755                 Extra = term()
1756                 Result = {ok,NewState,NewData} | Reason
1757                  OldState = NewState = state()
1758                  OldData = NewData = data()
1759                 Reason = term()
1760
1761          Note:
1762              This  callback  is optional, so callback modules need not export
1763              it. If a release upgrade/downgrade with Change  =  {advanced,Ex‐
1764              tra}  specified in the .appup file is made when code_change/4 is
1765              not implemented the process will crash with exit reason undef.
1766
1767
1768              This function is called by a gen_statem when it is to update its
1769              internal state during a release upgrade/downgrade, that is, when
1770              the instruction {update,Module,Change,...}, where Change =  {ad‐
1771              vanced,Extra}, is specified in the appup file. For more informa‐
1772              tion, see OTP Design Principles.
1773
1774              For an upgrade, OldVsn is Vsn, and for a  downgrade,  OldVsn  is
1775              {down,Vsn}.  Vsn  is  defined by the vsn attribute(s) of the old
1776              version of the callback module Module. If no such  attribute  is
1777              defined, the version is the checksum of the Beam file.
1778
1779              OldState and OldData is the internal state of the gen_statem.
1780
1781              Extra  is  passed  "as is" from the {advanced,Extra} part of the
1782              update instruction.
1783
1784              If successful, the function must  return  the  updated  internal
1785              state in an {ok,NewState,NewData} tuple.
1786
1787              If  the  function  returns a failure Reason, the ongoing upgrade
1788              fails and rolls back to the old release. Note that Reason cannot
1789              be  an  {ok,_,_} tuple since that will be regarded as a {ok,New‐
1790              State,NewData} tuple, and that a tuple  matching  {ok,_}  is  an
1791              also invalid failure Reason. It is recommended to use an atom as
1792              Reason since it will be wrapped in an {error,Reason} tuple.
1793
1794              Also note when upgrading a gen_statem, this function  and  hence
1795              the Change = {advanced,Extra} parameter in the appup file is not
1796              only needed to update the internal state or to act on the  Extra
1797              argument.  It  is  also needed if an upgrade or downgrade should
1798              change callback mode, or else the callback mode after  the  code
1799              change  will  not  be  honoured,  most probably causing a server
1800              crash.
1801
1802              If the server changes callback module using any of  the  actions
1803              change_callback_module,    push_callback_module   or   pop_call‐
1804              back_module, be aware that it is  always  the  current  callback
1805              module  that will get this callback call. That the current call‐
1806              back module handles the current state and data update should  be
1807              no  surprise,  but  it  must be able to handle even parts of the
1808              state and data that it is not familiar with, somehow.
1809
1810              In the supervisor child specification there is a list of modules
1811              which  is recommended to contain only the callback module. For a
1812              gen_statem with multiple callback modules there is no real  need
1813              to  list all of them, it may not even be possible since the list
1814              could change after code upgrade. If this list would contain only
1815              the  start callback module, as recommended, what is important is
1816              to upgrade that module whenever a synchronized code  replacement
1817              is done. Then the release handler concludes that an upgrade that
1818              upgrades that module needs to suspend, code change,  and  resume
1819              any  server  whose child specification declares that it is using
1820              that module. And again; the current callback module will get the
1821              Module:code_change/4 call.
1822
1823       Module:init(Args) -> Result(StateType)
1824
1825              Types:
1826
1827                 Args = term()
1828                  Result(StateType) = init_result(StateType)
1829
1830              Whenever   a   gen_statem   is   started  using  start_link/3,4,
1831              start_monitor/3,4, or start/3,4, this function is called by  the
1832              new  process  to  initialize the implementation state and server
1833              data.
1834
1835              Args is the Args argument provided to that start function.
1836
1837          Note:
1838              Note that if the gen_statem is started through proc_lib and  en‐
1839              ter_loop/4-6,  this  callback  will  never be called. Since this
1840              callback is not optional it can in that case be implemented as:
1841
1842              -spec init(_) -> no_return().
1843              init(Args) -> erlang:error(not_implemented, [Args]).
1844
1845
1846       Module:format_status(Status) -> NewStatus
1847
1848              Types:
1849
1850                 Status = format_status()
1851                 NewStatus = format_status()
1852
1853          Note:
1854              This callback is optional, so a callback module does not need to
1855              export  it. The gen_statem module provides a default implementa‐
1856              tion of this function that returns {State,Data}.
1857
1858              If this callback is exported but fails, to hide possibly  sensi‐
1859              tive   data,   the   default   function   will   instead  return
1860              {State,Info}, where Info says nothing but  the  fact  that  for‐
1861              mat_status/2 has crashed.
1862
1863
1864              This  function is called by a gen_statem process when any of the
1865              following apply:
1866
1867                * sys:get_status/1,2 is invoked to get the gen_statem status.
1868
1869                * The gen_statem process terminates abnormally and logs an er‐
1870                  ror.
1871
1872              This  function is useful for changing the form and appearance of
1873              the gen_statem status for these cases. A callback module wishing
1874              to change the sys:get_status/1,2 return value and how its status
1875              appears in termination error logs exports an  instance  of  for‐
1876              mat_status/1,  which  will  get  a map Status that describes the
1877              current states of the gen_statem, and shall return a map NewSta‐
1878              tus containing the same keys as the input map, but it may trans‐
1879              form some values.
1880
1881              One use case for this function is to return compact  alternative
1882              state  representations to avoid having large state terms printed
1883              in log files. Another is to hide sensitive data from being writ‐
1884              ten to the error log.
1885
1886              Example:
1887
1888              format_status(Status) ->
1889                maps:map(
1890                  fun(state,State) ->
1891                          maps:remove(private_key, State);
1892                     (message,{password, _Pass}) ->
1893                          {password, removed};
1894                     (_,Value) ->
1895                          Value
1896                  end, Status).
1897
1898
1899       Module:format_status(Opt, [PDict,State,Data]) -> Status
1900
1901              Types:
1902
1903                 Opt = normal | terminate
1904                 PDict = [{Key, Value}]
1905                  State = state()
1906                  Data = data()
1907                 Key = term()
1908                 Value = term()
1909                 Status = term()
1910
1911          Warning:
1912              This  callback  is deprecated, in new code use  format_status/1.
1913              If a format_status/1 callback exists, then  this  function  will
1914              never be called.
1915
1916
1917          Note:
1918              This callback is optional, so a callback module does not need to
1919              export it. The gen_statem module provides a default  implementa‐
1920              tion of this function that returns {State,Data}.
1921
1922              If  this callback is exported but fails, to hide possibly sensi‐
1923              tive  data,   the   default   function   will   instead   return
1924              {State,Info},  where  Info  says  nothing but the fact that for‐
1925              mat_status/2 has crashed.
1926
1927
1928              This function is called by a gen_statem process when any of  the
1929              following apply:
1930
1931                *
1932                   One  of sys:get_status/1,2 is invoked to get the gen_statem
1933                  status. Opt is set to the atom normal for this case.
1934
1935                *
1936                   The gen_statem terminates abnormally and logs an error. Opt
1937                  is set to the atom terminate for this case.
1938
1939              This  function is useful for changing the form and appearance of
1940              the gen_statem status for these cases. A callback module wishing
1941              to change the sys:get_status/1,2 return value and how its status
1942              appears in termination error logs exports an  instance  of  for‐
1943              mat_status/2, which returns a term describing the current status
1944              of the gen_statem.
1945
1946              PDict is the current value of  the  process  dictionary  of  the
1947              gen_statem.
1948
1949              State is the internal state of the gen_statem.
1950
1951              Data is the internal server data of the gen_statem.
1952
1953              The  function  is to return Status, a term that contains the ap‐
1954              propriate details  of  the  current  state  and  status  of  the
1955              gen_statem.  There  are  no  restrictions on the form Status can
1956              take, but for the sys:get_status/1,2 case (when Opt is  normal),
1957              the  recommended form for the Status value is [{data, [{"State",
1958              Term}]}], where Term provides relevant details of the gen_statem
1959              state.  Following  this  recommendation  is not required, but it
1960              makes the callback module status consistent with the rest of the
1961              sys:get_status/1,2 return value.
1962
1963              One use for this function is to return compact alternative state
1964              representations to avoid having large state terms printed in log
1965              files.  Another use is to hide sensitive data from being written
1966              to the error log.
1967
1968       Module:StateName(enter, OldState, Data) -> StateEnterResult(StateName)
1969       Module:StateName(EventType, EventContent, Data) -> StateFunctionResult
1970       Module:handle_event(enter,  OldState,  State,  Data)  ->  StateEnterRe‐
1971       sult(State)
1972       Module:handle_event(EventType,   EventContent,  State,  Data)  ->  Han‐
1973       dleEventResult
1974
1975              Types:
1976
1977                  EventType = event_type()
1978                 EventContent = term()
1979                  State = state()
1980                  Data = NewData = data()
1981                  StateEnterResult(StateName) = state_enter_result(StateName)
1982                  StateFunctionResult = event_handler_result(state_name())
1983                  StateEnterResult(State) = state_enter_result(State)
1984                  HandleEventResult = event_handler_result(state())
1985
1986              Whenever a gen_statem receives an event from call/2, cast/2,  or
1987              as  a  normal process message, one of these functions is called.
1988              If  callback  mode  is  state_functions,  Module:StateName/3  is
1989              called,   and   if   it  is  handle_event_function,  Module:han‐
1990              dle_event/4 is called.
1991
1992              If EventType is {call,From}, the caller waits for a  reply.  The
1993              reply  can be sent from this or from any other state callback by
1994              returning with {reply,From,Reply} in Actions, in Replies, or  by
1995              calling reply(From, Reply).
1996
1997              If  this  function returns with a next state that does not match
1998              equal (=/=) to the current state, all postponed events  are  re‐
1999              tried in the next state.
2000
2001              The  only difference between StateFunctionResult and HandleEven‐
2002              tResult is that for StateFunctionResult the next state  must  be
2003              an  atom,  but  for HandleEventResult there is no restriction on
2004              the next state.
2005
2006              For options that can be set and actions  that  can  be  done  by
2007              gen_statem after returning from this function, see action().
2008
2009              When the gen_statem runs with state enter calls, these functions
2010              are also called with arguments (enter, OldState, ...) during ev‐
2011              ery  state  change.  In this case there are some restrictions on
2012              the actions that may be  returned:  postpone()  is  not  allowed
2013              since a state enter call is not an event so there is no event to
2014              postpone, and {next_event,_,_} is not allowed since using  state
2015              enter  calls  should not affect how events are consumed and pro‐
2016              duced. You may also not change states from this call. Should you
2017              return  {next_state,NextState, ...} with NextState =/= State the
2018              gen_statem crashes. Note that it is actually allowed to use {re‐
2019              peat_state,  NewData,  ...} although it makes little sense since
2020              you immediately will be called again with a new state enter call
2021              making  this  just  a weird way of looping, and there are better
2022              ways to loop in Erlang. If you do not update  NewData  and  have
2023              some   loop   termination   condition,   or   if  you  use  {re‐
2024              peat_state_and_data, _} or repeat_state_and_data you have an in‐
2025              finite   loop!   You   are   advised  to  use  {keep_state,...},
2026              {keep_state_and_data,_} or  keep_state_and_data  since  changing
2027              states from a state enter call is not possible anyway.
2028
2029              Note the fact that you can use throw to return the result, which
2030              can   be   useful.   For    example    to    bail    out    with
2031              throw(keep_state_and_data)  from  deep  within complex code that
2032              cannot return {next_state,State,Data} because State or  Data  is
2033              no longer in scope.
2034
2035       Module:terminate(Reason, State, Data) -> Ignored
2036
2037              Types:
2038
2039                 Reason = normal | shutdown | {shutdown,term()} | term()
2040                 State = state()
2041                 Data = data()
2042                 Ignored = term()
2043
2044          Note:
2045              This  callback  is optional, so callback modules need not export
2046              it. The gen_statem  module  provides  a  default  implementation
2047              without cleanup.
2048
2049
2050              This function is called by a gen_statem when it is about to ter‐
2051              minate. It is to be the opposite of  Module:init/1  and  do  any
2052              necessary  cleaning  up.  When it returns, the gen_statem termi‐
2053              nates with Reason. The return value is ignored.
2054
2055              Reason is a term denoting the stop reason and State is  the  in‐
2056              ternal state of the gen_statem.
2057
2058              Reason  depends  on  why the gen_statem is terminating. If it is
2059              because another callback function has  returned,  a  stop  tuple
2060              {stop,Reason} in Actions, Reason has the value specified in that
2061              tuple. If it is because of a failure, Reason is the  error  rea‐
2062              son.
2063
2064              If  the  gen_statem is part of a supervision tree and is ordered
2065              by its supervisor to terminate, this  function  is  called  with
2066              Reason = shutdown if both the following conditions apply:
2067
2068                * The gen_statem has been set to trap exit signals.
2069
2070                * The  shutdown  strategy as defined in the supervisor's child
2071                  specification is an integer time-out value, not brutal_kill.
2072
2073              Even if the gen_statem is not part of a supervision  tree,  this
2074              function  is  called  if  it receives an 'EXIT' message from its
2075              parent. Reason is the same as in the 'EXIT' message.
2076
2077              Otherwise, the gen_statem is immediately terminated.
2078
2079              Notice that for any  other  reason  than  normal,  shutdown,  or
2080              {shutdown,Term},  the gen_statem is assumed to terminate because
2081              of an error and an error report is issued using logger(3).
2082
2083              When the gen_statem process exits, an exit signal with the  same
2084              reason is sent to linked processes and ports.
2085

SEE ALSO

2087       gen_event(3),  gen_fsm(3),  gen_server(3),  proc_lib(3), supervisor(3),
2088       sys(3).
2089
2090
2091
2092Ericsson AB                       stdlib 4.2                     gen_statem(3)
Impressum