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
44           actions 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
48       really 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
92       between  the  behavior  functions and the callback functions is as fol‐
93       lows:
94
95       gen_statem module            Callback module
96       -----------------            ---------------
97       gen_statem:start
98       gen_statem:start_monitor
99       gen_statem:start_link -----> Module:init/1
100
101       Server start or code change
102                             -----> Module:callback_mode/0
103
104       gen_statem:stop       -----> Module:terminate/3
105
106       gen_statem:call
107       gen_statem:cast
108       gen_statem:send_request
109       erlang:send
110       erlang:'!'            -----> Module:StateName/3
111                                    Module:handle_event/4
112
113       -                     -----> Module:terminate/3
114
115       -                     -----> Module:code_change/4
116
117       Events are of different types, so the callback functions can  know  the
118       origin of an event and how to respond.
119
120       If  a  callback  function  fails or returns a bad value, the gen_statem
121       terminates, unless otherwise stated. However,  an  exception  of  class
122       throw  is not regarded as an error but as a valid return from all call‐
123       back functions.
124
125       The state callback for a specific state in a gen_statem is the callback
126       function  that  is  called for all events in this state. It is selected
127       depending on which callback mode that the callback module defines  with
128       the callback function Module:callback_mode/0.
129
130       When  the  callback  mode is state_functions, the state must be an atom
131       and is used as the state callback name;  see  Module:StateName/3.  This
132       co-locates  all  code  for  a  specific  state  in  one function as the
133       gen_statem engine branches depending on state name. Note the fact  that
134       the callback function Module:terminate/3 makes the state name terminate
135       unusable in this mode.
136
137       When the callback mode is handle_event_function, the state can  be  any
138       term  and  the state callback name is Module:handle_event/4. This makes
139       it easy to branch depending on state or event as you desire. Be careful
140       about  which events you handle in which states so that you do not acci‐
141       dentally postpone an event forever creating an infinite busy loop.
142
143       When gen_statem receives a process message  it  is  converted  into  an
144       event and the state callback is called with the event as two arguments:
145       type and content. When the state callback has processed  the  event  it
146       returns  to  gen_statem  which  does  a state transition. If this state
147       transition is to a different state, that is: NextState =/= State, it is
148       a state change.
149
150       The state callback may return transition actions for gen_statem to exe‐
151       cute  during  the  state  transition,  for  example  to  reply   to   a
152       gen_statem:call/2,3.
153
154       One  of  the  possible  transition  actions  is to postpone the current
155       event. Then it is not retried in  the  current  state.  The  gen_statem
156       engine  keeps  a  queue of events divided into the postponed events and
157       the events still to process. After a state change  the  queue  restarts
158       with the postponed events.
159
160       The  gen_statem  event  queue model is sufficient to emulate the normal
161       process message queue with selective receive. Postponing an event  cor‐
162       responds to not matching it in a receive statement, and changing states
163       corresponds to entering a new receive statement.
164
165       The state callback can  insert  events  using  the  transition  actions
166       next_event and such an event is inserted in the event queue as the next
167       to call the state callback with. That is, as if it is the oldest incom‐
168       ing  event.  A  dedicated  event_type()  internal  can be used for such
169       events making them impossible to mistake for external events.
170
171       Inserting an event replaces the trick of calling your  own  state  han‐
172       dling functions that you often would have to resort to in, for example,
173       gen_fsm to force processing an inserted event before others.
174
175       The gen_statem engine can automatically make a specialized call to  the
176       state callback whenever a new state is entered; see state_enter(). This
177       is for writing code common to all state entries. Another way to  do  it
178       is to explicitly insert an event at the state transition, and/or to use
179       a dedicated state transition function, but that is something  you  will
180       have  to  remember  at every state transition to the state(s) that need
181       it.
182
183   Note:
184       If you in gen_statem, for example, postpone an event in one  state  and
185       then  call  another  state callback of yours, you have not done a state
186       change and hence the postponed event is not retried, which  is  logical
187       but can be confusing.
188
189
190       For the details of a state transition, see type transition_option().
191
192       A  gen_statem handles system messages as described in sys. The sys mod‐
193       ule can be used for debugging a gen_statem.
194
195       Notice that a gen_statem does not trap exit signals automatically, this
196       must  be  explicitly  initiated  in  the  callback  module  (by calling
197       process_flag(trap_exit, true).
198
199       Unless otherwise stated, all functions in this module fail if the spec‐
200       ified gen_statem does not exist or if bad arguments are specified.
201
202       The  gen_statem  process  can  go into hibernation; see proc_lib:hiber‐
203       nate/3. It is done when a state  callback  or  Module:init/1  specifies
204       hibernate  in  the returned Actions list. This feature can be useful to
205       reclaim process heap memory while the server is expected to be idle for
206       a long time. However, use this feature with care, as hibernation can be
207       too costly to use after every event; see erlang:hibernate/3.
208
209       There is also a server  start  option  {hibernate_after,  Timeout}  for
210       start/3,4,  start_monitor/3,4, start_link/3,4 or enter_loop/4,5,6, that
211       may be used to automatically hibernate the server.
212

EXAMPLE

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

DATA TYPES

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

EXPORTS

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

CALLBACK FUNCTIONS

1277       The following functions are to be exported from a  gen_statem  callback
1278       module.
1279

EXPORTS

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

SEE ALSO

1589       gen_event(3),  gen_fsm(3),  gen_server(3),  proc_lib(3), supervisor(3),
1590       sys(3).
1591
1592
1593
1594Ericsson AB                      stdlib 3.14.1                   gen_statem(3)
Impressum