1gen_statem(3) Erlang Module Definition gen_statem(3)
2
3
4
6 gen_statem - Generic state machine behavior.
7
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
213 The following example shows a simple pushbutton model for a toggling
214 pushbutton implemented with callback mode state_functions. You can push
215 the button and it replies if it went on or off, and you can ask for a
216 count of how many times it has been pushed to switch on.
217
218 The following is the complete callback module file pushbutton.erl:
219
220 -module(pushbutton).
221 -behaviour(gen_statem).
222
223 -export([start/0,push/0,get_count/0,stop/0]).
224 -export([terminate/3,code_change/4,init/1,callback_mode/0]).
225 -export([on/3,off/3]).
226
227 name() -> pushbutton_statem. % The registered server name
228
229 %% API. This example uses a registered name name()
230 %% and does not link to the caller.
231 start() ->
232 gen_statem:start({local,name()}, ?MODULE, [], []).
233 push() ->
234 gen_statem:call(name(), push).
235 get_count() ->
236 gen_statem:call(name(), get_count).
237 stop() ->
238 gen_statem:stop(name()).
239
240 %% Mandatory callback functions
241 terminate(_Reason, _State, _Data) ->
242 void.
243 code_change(_Vsn, State, Data, _Extra) ->
244 {ok,State,Data}.
245 init([]) ->
246 %% Set the initial state + data. Data is used only as a counter.
247 State = off, Data = 0,
248 {ok,State,Data}.
249 callback_mode() -> state_functions.
250
251 %%% state callback(s)
252
253 off({call,From}, push, Data) ->
254 %% Go to 'on', increment count and reply
255 %% that the resulting status is 'on'
256 {next_state,on,Data+1,[{reply,From,on}]};
257 off(EventType, EventContent, Data) ->
258 handle_event(EventType, EventContent, Data).
259
260 on({call,From}, push, Data) ->
261 %% Go to 'off' and reply that the resulting status is 'off'
262 {next_state,off,Data,[{reply,From,off}]};
263 on(EventType, EventContent, Data) ->
264 handle_event(EventType, EventContent, Data).
265
266 %% Handle events common to all states
267 handle_event({call,From}, get_count, Data) ->
268 %% Reply with the current count
269 {keep_state,Data,[{reply,From,Data}]};
270 handle_event(_, _, Data) ->
271 %% Ignore all other events
272 {keep_state,Data}.
273
274
275 The following is a shell session when running it:
276
277 1> pushbutton:start().
278 {ok,<0.36.0>}
279 2> pushbutton:get_count().
280 0
281 3> pushbutton:push().
282 on
283 4> pushbutton:get_count().
284 1
285 5> pushbutton:push().
286 off
287 6> pushbutton:get_count().
288 1
289 7> pushbutton:stop().
290 ok
291 8> pushbutton:push().
292 ** exception exit: {noproc,{gen_statem,call,[pushbutton_statem,push,infinity]}}
293 in function gen:do_for_proc/2 (gen.erl, line 261)
294 in call from gen_statem:call/3 (gen_statem.erl, line 386)
295
296
297 To compare styles, here follows the same example using callback mode
298 handle_event_function, or rather the code to replace after function
299 init/1 of the pushbutton.erl example file above:
300
301 callback_mode() -> handle_event_function.
302
303 %%% state callback(s)
304
305 handle_event({call,From}, push, off, Data) ->
306 %% Go to 'on', increment count and reply
307 %% that the resulting status is 'on'
308 {next_state,on,Data+1,[{reply,From,on}]};
309 handle_event({call,From}, push, on, Data) ->
310 %% Go to 'off' and reply that the resulting status is 'off'
311 {next_state,off,Data,[{reply,From,off}]};
312 %%
313 %% Event handling common to all states
314 handle_event({call,From}, get_count, State, Data) ->
315 %% Reply with the current count
316 {next_state,State,Data,[{reply,From,Data}]};
317 handle_event(_, _, State, Data) ->
318 %% Ignore all other events
319 {next_state,State,Data}.
320
321
323 server_name() =
324 {global, GlobalName :: term()} |
325 {via, RegMod :: module(), Name :: term()} |
326 {local, atom()}
327
328 Name specification to use when starting a gen_statem server. See
329 start_link/3 and server_ref() below.
330
331 server_ref() =
332 pid() |
333 (LocalName :: atom()) |
334 {Name :: atom(), Node :: atom()} |
335 {global, GlobalName :: term()} |
336 {via, RegMod :: module(), ViaName :: term()}
337
338 Server specification to use when addressing a gen_statem server.
339 See call/2 and server_name() above.
340
341 It can be:
342
343 pid() | LocalName:
344 The gen_statem is locally registered.
345
346 {Name,Node}:
347 The gen_statem is locally registered on another node.
348
349 {global,GlobalName}:
350 The gen_statem is globally registered in global.
351
352 {via,RegMod,ViaName}:
353 The gen_statem is registered in an alternative process reg‐
354 istry. The registry callback module RegMod is to export
355 functions register_name/2, unregister_name/1,
356 whereis_name/1, and send/2, which are to behave like the
357 corresponding functions in global. Thus, {via,global,Global‐
358 Name} is the same as {global,GlobalName}.
359
360 start_opt() =
361 {timeout, Time :: timeout()} |
362 {spawn_opt, [proc_lib:start_spawn_option()]} |
363 enter_loop_opt()
364
365 Options that can be used when starting a gen_statem server
366 through, for example, start_link/3.
367
368 start_ret() = {ok, pid()} | ignore | {error, term()}
369
370 Return value from the start() and start_link() functions, for
371 example, start_link/3.
372
373 start_mon_ret() =
374 {ok, {pid(), reference()}} | ignore | {error, term()}
375
376 Return value from the start_monitor() functions.
377
378 enter_loop_opt() =
379 {hibernate_after, HibernateAfterTimeout :: timeout()} |
380 {debug, Dbgs :: [sys:debug_option()]}
381
382 Options that can be used when starting a gen_statem server
383 through, enter_loop/4-6.
384
385 hibernate_after:
386 HibernateAfterTimeout specifies that the gen_statem process
387 awaits any message for HibernateAfterTimeout milliseconds
388 and if no message is received, the process goes into hiber‐
389 nation automatically (by calling proc_lib:hibernate/3).
390
391 debug:
392 For every entry in Dbgs, the corresponding function in sys
393 is called.
394
395 from() = {To :: pid(), Tag :: term()}
396
397 Destination to use when replying through, for example, the ac‐
398 tion() {reply,From,Reply} to a process that has called the
399 gen_statem server using call/2.
400
401 state() = state_name() | term()
402
403 If the callback mode is handle_event_function, the state can be
404 any term. After a state change (NextState =/= State), all post‐
405 poned events are retried.
406
407 state_name() = atom()
408
409 If the callback mode is state_functions, the state must be an
410 atom. After a state change (NextState =/= State), all postponed
411 events are retried. Note that the state terminate is not possi‐
412 ble to use since it would collide with the optional callback
413 function Module:terminate/3.
414
415 data() = term()
416
417 A term in which the state machine implementation is to store any
418 server data it needs. The difference between this and the
419 state() itself is that a change in this data does not cause
420 postponed events to be retried. Hence, if a change in this data
421 would change the set of events that are handled, then that data
422 item is to be made a part of the state.
423
424 event_type() =
425 external_event_type() | timeout_event_type() | internal
426
427 There are 3 categories of events: external, timeout, and inter‐
428 nal.
429
430 internal events can only be generated by the state machine it‐
431 self through the transition action next_event.
432
433 external_event_type() = {call, From :: from()} | cast | info
434
435 External events are of 3 types: {call,From}, cast, or info. Type
436 call originates from the API functions call/2 and send_re‐
437 quest/2. For calls, the event contains whom to reply to. Type
438 cast originates from the API function cast/2. Type info origi‐
439 nates from regular process messages sent to the gen_statem.
440
441 timeout_event_type() =
442 timeout | {timeout, Name :: term()} | state_timeout
443
444 There are 3 types of time-out events that the state machine can
445 generate for itself with the corresponding timeout_action()s.
446
447 callback_mode_result() =
448 callback_mode() | [callback_mode() | state_enter()]
449
450 This is the return type from Module:callback_mode/0 and selects
451 callback mode and whether to do state enter calls, or not.
452
453 callback_mode() = state_functions | handle_event_function
454
455 The callback mode is selected with the return value from Mod‐
456 ule:callback_mode/0:
457
458 state_functions:
459 The state must be of type state_name() and one callback
460 function per state, that is, Module:StateName/3, is used.
461
462 handle_event_function:
463 The state can be any term and the callback function Mod‐
464 ule:handle_event/4 is used for all states.
465
466 The function Module:callback_mode/0 is called when starting the
467 gen_statem, after code change and after changing the callback
468 module with any of the actions change_callback_module,
469 push_callback_module or pop_callback_module. The result is
470 cached for subsequent calls to state callbacks.
471
472 state_enter() = state_enter
473
474 Whether the state machine should use state enter calls or not is
475 selected when starting the gen_statem and after code change us‐
476 ing the return value from Module:callback_mode/0.
477
478 If Module:callback_mode/0 returns a list containing state_enter,
479 the gen_statem engine will, at every state change, call the
480 state callback with arguments (enter, OldState, Data) or (enter,
481 OldState, State, Data), depending on the callback mode. This may
482 look like an event but is really a call performed after the pre‐
483 vious state callback returned and before any event is delivered
484 to the new state callback. See Module:StateName/3 and Mod‐
485 ule:handle_event/4. Such a call can be repeated by returning a
486 repeat_state or repeat_state_and_data tuple from the state call‐
487 back.
488
489 If Module:callback_mode/0 does not return such a list, no state
490 enter calls are done.
491
492 If Module:code_change/4 should transform the state, it is re‐
493 garded as a state rename and not a state change, which will not
494 cause a state enter call.
495
496 Note that a state enter call will be done right before entering
497 the initial state even though this actually is not a state
498 change. In this case OldState =:= State, which cannot happen for
499 a subsequent state change, but will happen when repeating the
500 state enter call.
501
502 transition_option() =
503 postpone() |
504 hibernate() |
505 event_timeout() |
506 generic_timeout() |
507 state_timeout()
508
509 Transition options can be set by actions and modify the state
510 transition. The state transition takes place when the state
511 callback has processed an event and returns. Here are the se‐
512 quence of steps for a state transition:
513
514 * All returned actions are processed in order of appearance.
515 In this step all replies generated by any reply_action() are
516 sent. Other actions set transition_option()s that come into
517 play in subsequent steps.
518
519 * If state enter calls are used, and either it is the initial
520 state or one of the callback results repeat_state_and_data
521 or repeat_state_and_data is used the gen_statem engine calls
522 the current state callback with arguments (enter, State,
523 Data) or (enter, State, State, Data) (depending on callback
524 mode) and when it returns starts again from the top of this
525 sequence.
526
527 If state enter calls are used, and the state changes the
528 gen_statem engine calls the new state callback with argu‐
529 ments (enter, OldState, Data) or (enter, OldState, State,
530 Data) (depending on callback mode) and when it returns
531 starts again from the top of this sequence.
532
533 * If postpone() is true, the current event is postponed.
534
535 * If this is a state change, the queue of incoming events is
536 reset to start with the oldest postponed.
537
538 * All events stored with action() next_event are inserted to
539 be processed before previously queued events.
540
541 * Time-out timers event_timeout(), generic_timeout() and
542 state_timeout() are handled. Time-outs with zero time are
543 guaranteed to be delivered to the state machine before any
544 external not yet received event so if there is such a time-
545 out requested, the corresponding time-out zero event is en‐
546 queued as the newest received event; that is after already
547 queued events such as inserted and postponed events.
548
549 Any event cancels an event_timeout() so a zero time event
550 time-out is only generated if the event queue is empty.
551
552 A state change cancels a state_timeout() and any new transi‐
553 tion option of this type belongs to the new state, that is;
554 a state_timeout() applies to the state the state machine en‐
555 ters.
556
557 * If there are enqueued events the state callback for the pos‐
558 sibly new state is called with the oldest enqueued event,
559 and we start again from the top of this sequence.
560
561 * Otherwise the gen_statem goes into receive or hibernation
562 (if hibernate() is true) to wait for the next message. In
563 hibernation the next non-system event awakens the
564 gen_statem, or rather the next incoming message awakens the
565 gen_statem, but if it is a system event it goes right back
566 into hibernation. When a new message arrives the state call‐
567 back is called with the corresponding event, and we start
568 again from the top of this sequence.
569
570 postpone() = boolean()
571
572 If true, postpones the current event and retries it after a
573 state change (NextState =/= State).
574
575 hibernate() = boolean()
576
577 If true, hibernates the gen_statem by calling proc_lib:hiber‐
578 nate/3 before going into receive to wait for a new external
579 event.
580
581 Note:
582 If there are enqueued events to process when hibrnation is re‐
583 quested, this is optimized by not hibernating but instead call‐
584 ing erlang:garbage_collect/0 to simulate that the gen_statem en‐
585 tered hibernation and immediately got awakened by an enqueued
586 event.
587
588
589 event_timeout() = timeout() | integer()
590
591 Starts a timer set by enter_action() timeout. When the timer ex‐
592 pires an event of event_type() timeout will be generated. See
593 erlang:start_timer/4 for how Time and Options are interpreted.
594 Future erlang:start_timer/4 Options will not necessarily be sup‐
595 ported.
596
597 Any event that arrives cancels this time-out. Note that a re‐
598 tried or inserted event counts as arrived. So does a state time-
599 out zero event, if it was generated before this time-out is re‐
600 quested.
601
602 If Time is infinity, no timer is started, as it never would ex‐
603 pire anyway.
604
605 If Time is relative and 0 no timer is actually started, instead
606 the the time-out event is enqueued to ensure that it gets pro‐
607 cessed before any not yet received external event, but after al‐
608 ready queued events.
609
610 Note that it is not possible nor needed to cancel this time-out,
611 as it is cancelled automatically by any other event.
612
613 generic_timeout() = timeout() | integer()
614
615 Starts a timer set by enter_action() {timeout,Name}. When the
616 timer expires an event of event_type() {timeout,Name} will be
617 generated. See erlang:start_timer/4 for how Time and Options are
618 interpreted. Future erlang:start_timer/4 Options will not neces‐
619 sarily be supported.
620
621 If Time is infinity, no timer is started, as it never would ex‐
622 pire anyway.
623
624 If Time is relative and 0 no timer is actually started, instead
625 the the time-out event is enqueued to ensure that it gets pro‐
626 cessed before any not yet received external event.
627
628 Setting a timer with the same Name while it is running will
629 restart it with the new time-out value. Therefore it is possible
630 to cancel a specific time-out by setting it to infinity.
631
632 state_timeout() = timeout() | integer()
633
634 Starts a timer set by enter_action() state_timeout. When the
635 timer expires an event of event_type() state_timeout will be
636 generated. See erlang:start_timer/4 for how Time and Options are
637 interpreted. Future erlang:start_timer/4 Options will not neces‐
638 sarily be supported.
639
640 If Time is infinity, no timer is started, as it never would ex‐
641 pire anyway.
642
643 If Time is relative and 0 no timer is actually started, instead
644 the the time-out event is enqueued to ensure that it gets pro‐
645 cessed before any not yet received external event.
646
647 Setting this timer while it is running will restart it with the
648 new time-out value. Therefore it is possible to cancel this
649 time-out by setting it to infinity.
650
651 timeout_option() = {abs, Abs :: boolean()}
652
653 If Abs is true an absolute timer is started, and if it is false
654 a relative, which is the default. See erlang:start_timer/4 for
655 details.
656
657 action() =
658 postpone |
659 {postpone, Postpone :: postpone()} |
660 {next_event,
661 EventType :: event_type(),
662 EventContent :: term()} |
663 {change_callback_module, NewModule :: module()} |
664 {push_callback_module, NewModule :: module()} |
665 pop_callback_module |
666 enter_action()
667
668 These transition actions can be invoked by returning them from
669 the state callback when it is called with an event, from Mod‐
670 ule:init/1 or by giving them to enter_loop/5,6.
671
672 Actions are executed in the containing list order.
673
674 Actions that set transition options override any previous of
675 the same type, so the last in the containing list wins. For ex‐
676 ample, the last postpone() overrides any previous postpone() in
677 the list.
678
679 postpone:
680 Sets the transition_option() postpone() for this state tran‐
681 sition. This action is ignored when returned from Mod‐
682 ule:init/1 or given to enter_loop/5,6, as there is no event
683 to postpone in those cases.
684
685 next_event:
686 This action does not set any transition_option() but instead
687 stores the specified EventType and EventContent for inser‐
688 tion after all actions have been executed.
689
690 The stored events are inserted in the queue as the next to
691 process before any already queued events. The order of these
692 stored events is preserved, so the first next_event in the
693 containing list becomes the first to process.
694
695 An event of type internal is to be used when you want to re‐
696 liably distinguish an event inserted this way from any ex‐
697 ternal event.
698
699 change_callback_module:
700 Changes the callback module to NewModule which will be used
701 when calling all subsequent state callbacks.
702
703 The gen_statem engine will find out the callback mode of
704 NewModule by calling NewModule:callback_mode/0 before the
705 next state callback.
706
707 Changing the callback module does not affect the state tran‐
708 sition in any way, it only changes which module that handles
709 the events. Be aware that all relevant callback functions in
710 NewModule such as the state callback, NewMod‐
711 ule:code_change/4, NewModule:format_status/2 and NewMod‐
712 ule:terminate/3 must be able to handle the state and data
713 from the old module.
714
715 push_callback_module:
716 Pushes the current callback module to the top of an internal
717 stack of callback modules and changes the callback module to
718 NewModule. Otherwise like {change_callback_module, NewMod‐
719 ule} above.
720
721 pop_callback_module:
722 Pops the top module from the internal stack of callback
723 modules and changes the callback module to be the popped
724 module. If the stack is empty the server fails. Otherwise
725 like {change_callback_module, NewModule} above.
726
727 enter_action() =
728 hibernate |
729 {hibernate, Hibernate :: hibernate()} |
730 timeout_action() |
731 reply_action()
732
733 These transition actions can be invoked by returning them from
734 the state callback, from Module:init/1 or by giving them to en‐
735 ter_loop/5,6.
736
737 Actions are executed in the containing list order.
738
739 Actions that set transition options override any previous of the
740 same type, so the last in the containing list wins. For example,
741 the last event_timeout() overrides any previous event_timeout()
742 in the list.
743
744 hibernate:
745 Sets the transition_option() hibernate() for this state
746 transition.
747
748 timeout_action() =
749 (Time :: event_timeout()) |
750 {timeout, Time :: event_timeout(), EventContent :: term()} |
751 {timeout,
752 Time :: event_timeout(),
753 EventContent :: term(),
754 Options :: timeout_option() | [timeout_option()]} |
755 {{timeout, Name :: term()},
756 Time :: generic_timeout(),
757 EventContent :: term()} |
758 {{timeout, Name :: term()},
759 Time :: generic_timeout(),
760 EventContent :: term(),
761 Options :: timeout_option() | [timeout_option()]} |
762 {state_timeout,
763 Time :: state_timeout(),
764 EventContent :: term()} |
765 {state_timeout,
766 Time :: state_timeout(),
767 EventContent :: term(),
768 Options :: timeout_option() | [timeout_option()]} |
769 timeout_cancel_action() |
770 timeout_update_action()
771
772 These transition actions can be invoked by returning them from
773 the state callback, from Module:init/1 or by giving them to en‐
774 ter_loop/5,6.
775
776 These time-out actions sets time-out transition options.
777
778 Time:
779 Short for {timeout,Time,Time}, that is, the time-out message
780 is the time-out time. This form exists to make the state
781 callback return value {next_state,NextState,NewData,Time}
782 allowed like for gen_fsm.
783
784 timeout:
785 Sets the transition_option() event_timeout() to Time with
786 EventContent and time-out options Options.
787
788 {timeout,Name}:
789 Sets the transition_option() generic_timeout() to Time for
790 Name with EventContent and time-out options Options.
791
792 state_timeout:
793 Sets the transition_option() state_timeout() to Time with
794 EventContent and time-out options Options.
795
796 timeout_cancel_action() =
797 {timeout, cancel} |
798 {{timeout, Name :: term()}, cancel} |
799 {state_timeout, cancel}
800
801 This is a shorter and clearer form of timeout_action() with
802 Time = infinity which cancels a time-out.
803
804 timeout_update_action() =
805 {timeout, update, EventContent :: term()} |
806 {{timeout, Name :: term()}, update, EventContent :: term()} |
807 {state_timeout, update, EventContent :: term()}
808
809 Updates a time-out with a new EventContent. See timeout_ac‐
810 tion() for how to start a time-out.
811
812 If no time-out of the same type is active instead insert the
813 time-out event just like when starting a time-out with relative
814 Time = 0.
815
816 reply_action() = {reply, From :: from(), Reply :: term()}
817
818 This transition action can be invoked by returning it from the
819 state callback, from Module:init/1 or by giving it to en‐
820 ter_loop/5,6.
821
822 It does not set any transition_option() but instead replies to a
823 caller waiting for a reply in call/2. From must be the term from
824 argument {call,From} in a call to a state callback.
825
826 Note that using this action from Module:init/1 or enter_loop/5,6
827 would be weird on the border of witchcraft since there has been
828 no earlier call to a state callback in this server.
829
830 init_result(StateType) =
831 {ok, State :: StateType, Data :: data()} |
832 {ok,
833 State :: StateType,
834 Data :: data(),
835 Actions :: [action()] | action()} |
836 ignore |
837 {stop, Reason :: term()}
838
839 For a succesful initialization, State is the initial state() and
840 Data the initial server data() of the gen_statem.
841
842 The Actions are executed when entering the first state just as
843 for a state callback, except that the action postpone is forced
844 to false since there is no event to postpone.
845
846 For an unsuccesful initialization, {stop,Reason} or ignore
847 should be used; see start_link/3,4.
848
849 state_enter_result(State) =
850 {next_state, State, NewData :: data()} |
851 {next_state, State,
852 NewData :: data(),
853 Actions :: [enter_action()] | enter_action()} |
854 state_callback_result(enter_action())
855
856 State is the current state and it cannot be changed since the
857 state callback was called with a state enter call.
858
859 next_state:
860 The gen_statem does a state transition to State, which has
861 to be the current state, sets NewData, and executes all Ac‐
862 tions.
863
864 event_handler_result(StateType) =
865 {next_state, NextState :: StateType, NewData :: data()} |
866 {next_state,
867 NextState :: StateType,
868 NewData :: data(),
869 Actions :: [action()] | action()} |
870 state_callback_result(action())
871
872 StateType is state_name() if callback mode is state_functions,
873 or state() if callback mode is handle_event_function.
874
875 next_state:
876 The gen_statem does a state transition to NextState (which
877 can be the same as the current state), sets NewData, and ex‐
878 ecutes all Actions. If NextState =/= CurrentState the state
879 transition is a state change.
880
881 state_callback_result(ActionType) =
882 {keep_state, NewData :: data()} |
883 {keep_state,
884 NewData :: data(),
885 Actions :: [ActionType] | ActionType} |
886 keep_state_and_data |
887 {keep_state_and_data, Actions :: [ActionType] | ActionType} |
888 {repeat_state, NewData :: data()} |
889 {repeat_state,
890 NewData :: data(),
891 Actions :: [ActionType] | ActionType} |
892 repeat_state_and_data |
893 {repeat_state_and_data, Actions :: [ActionType] | ActionType} |
894 stop |
895 {stop, Reason :: term()} |
896 {stop, Reason :: term(), NewData :: data()} |
897 {stop_and_reply,
898 Reason :: term(),
899 Replies :: [reply_action()] | reply_action()} |
900 {stop_and_reply,
901 Reason :: term(),
902 Replies :: [reply_action()] | reply_action(),
903 NewData :: data()}
904
905 ActionType is enter_action() if the state callback was called
906 with a state enter call and action() if the state callback was
907 called with an event.
908
909 keep_state:
910 The same as {next_state,CurrentState,NewData,Actions}.
911
912 keep_state_and_data:
913 The same as {keep_state,CurrentData,Actions}.
914
915 repeat_state:
916 If the gen_statem runs with state enter calls, the state en‐
917 ter call is repeated, see type transition_option(), other
918 than that repeat_state is the same as keep_state.
919
920 repeat_state_and_data:
921 The same as {repeat_state,CurrentData,Actions}.
922
923 stop:
924 Terminates the gen_statem by calling Module:terminate/3 with
925 Reason and NewData, if specified.
926
927 stop_and_reply:
928 Sends all Replies, then terminates the gen_statem by calling
929 Module:terminate/3 with Reason and NewData, if specified.
930
931 All these terms are tuples or atoms and this property will hold
932 in any future version of gen_statem.
933
934 request_id() = term()
935
936 A request handle, see send_request/2 for details.
937
939 call(ServerRef :: server_ref(), Request :: term()) ->
940 Reply :: term()
941
942 call(ServerRef :: server_ref(),
943 Request :: term(),
944 Timeout ::
945 timeout() |
946 {clean_timeout, T :: timeout()} |
947 {dirty_timeout, T :: timeout()}) ->
948 Reply :: term()
949
950 Makes a synchronous call to the gen_statem ServerRef by sending
951 a request and waiting until its reply arrives. The gen_statem
952 calls the state callback with event_type() {call,From} and event
953 content Request.
954
955 A Reply is generated when a state callback returns with {re‐
956 ply,From,Reply} as one action(), and that Reply becomes the re‐
957 turn value of this function.
958
959 Timeout is an integer > 0, which specifies how many milliseconds
960 to wait for a reply, or the atom infinity to wait indefinitely,
961 which is the default. If no reply is received within the speci‐
962 fied time, the function call fails.
963
964 Note:
965 For Timeout < infinity, to avoid getting a late reply in the
966 caller's inbox if the caller should catch exceptions, this func‐
967 tion spawns a proxy process that does the call. A late reply
968 gets delivered to the dead proxy process, hence gets discarded.
969 This is less efficient than using Timeout == infinity.
970
971
972 Timeout can also be a tuple {clean_timeout,T} or {dirty_time‐
973 out,T}, where T is the time-out time. {clean_timeout,T} works
974 like just T described in the note above and uses a proxy process
975 while {dirty_timeout,T} bypasses the proxy process which is more
976 lightweight.
977
978 Note:
979 If you combine catching exceptions from this function with
980 {dirty_timeout,T} to avoid that the calling process dies when
981 the call times out, you will have to be prepared to handle a
982 late reply. Note that there is an odd chance to get a late reply
983 even with {dirty_timeout,infinity} or infinity for example in
984 the event of network problems. So why not just let the calling
985 process die by not catching the exception?
986
987
988 The call can also fail, for example, if the gen_statem dies be‐
989 fore or during this function call.
990
991 cast(ServerRef :: server_ref(), Msg :: term()) -> ok
992
993 Sends an asynchronous event to the gen_statem ServerRef and re‐
994 turns ok immediately, ignoring if the destination node or
995 gen_statem does not exist. The gen_statem calls the state call‐
996 back with event_type() cast and event content Msg.
997
998 check_response(Msg :: term(), RequestId :: request_id()) ->
999 {reply, Reply :: term()} |
1000 no_reply |
1001 {error, {term(), server_ref()}}
1002
1003 This function is used to check if a previously received message,
1004 for example by receive or handle_info/2, is a result of a re‐
1005 quest made with send_request/2. If Msg is a reply to the handle
1006 RequestId the result of the request is returned in Reply. Other‐
1007 wise returns no_reply and no cleanup is done, and thus the func‐
1008 tion shall be invoked repeatedly until a reply is returned.
1009
1010 The return value Reply is generated when a state callback re‐
1011 turns with {reply,From,Reply} as one action(), and that Reply
1012 becomes the return value of this function.
1013
1014 The function returns an error if the gen_statem dies before or
1015 during this request.
1016
1017 enter_loop(Module :: module(),
1018 Opts :: [enter_loop_opt()],
1019 State :: state(),
1020 Data :: data()) ->
1021 no_return()
1022
1023 The same as enter_loop/6 with Actions = [] except that no
1024 server_name() must have been registered. This creates an anony‐
1025 mous server.
1026
1027 enter_loop(Module :: module(),
1028 Opts :: [enter_loop_opt()],
1029 State :: state(),
1030 Data :: data(),
1031 Server_or_Actions :: server_name() | pid() | [action()]) ->
1032 no_return()
1033
1034 If Server_or_Actions is a list(), the same as enter_loop/6 ex‐
1035 cept that no server_name() must have been registered and Actions
1036 = Server_or_Actions. This creates an anonymous server.
1037
1038 Otherwise the same as enter_loop/6 with Server = Server_or_Ac‐
1039 tions and Actions = [].
1040
1041 enter_loop(Module :: module(),
1042 Opts :: [enter_loop_opt()],
1043 State :: state(),
1044 Data :: data(),
1045 Server :: server_name() | pid(),
1046 Actions :: [action()] | action()) ->
1047 no_return()
1048
1049 Makes the calling process become a gen_statem. Does not return,
1050 instead the calling process enters the gen_statem receive loop
1051 and becomes a gen_statem server. The process must have been
1052 started using one of the start functions in proc_lib. The user
1053 is responsible for any initialization of the process, including
1054 registering a name for it.
1055
1056 This function is useful when a more complex initialization pro‐
1057 cedure is needed than the gen_statem behavior provides.
1058
1059 Module, Opts have the same meaning as when calling
1060 start[_link|_monitor]/3,4.
1061
1062 If Server is self() an anonymous server is created just as when
1063 using start[_link|_monitor]/3. If Server is a server_name() a
1064 named server is created just as when using start[_link|_moni‐
1065 tor]/4. However, the server_name() name must have been regis‐
1066 tered accordingly before this function is called.
1067
1068 State, Data, and Actions have the same meanings as in the return
1069 value of Module:init/1. Also, the callback module does not need
1070 to export a Module:init/1 function.
1071
1072 The function fails if the calling process was not started by a
1073 proc_lib start function, or if it is not registered according to
1074 server_name().
1075
1076 reply(Replies :: [reply_action()] | reply_action()) -> ok
1077
1078 reply(From :: from(), Reply :: term()) -> ok
1079
1080 This function can be used by a gen_statem to explicitly send a
1081 reply to a process that waits in call/2 when the reply cannot be
1082 defined in the return value of a state callback.
1083
1084 From must be the term from argument {call,From} to the state
1085 callback. A reply or multiple replies canalso be sent using one
1086 or several reply_action()s from a state callback.
1087
1088 Note:
1089 A reply sent with this function is not visible in sys debug out‐
1090 put.
1091
1092
1093 send_request(ServerRef :: server_ref(), Request :: term()) ->
1094 RequestId :: request_id()
1095
1096 Sends a request to the gen_statem ServerRef and returns a handle
1097 RequestId.
1098
1099 The return value RequestId shall later be used with wait_re‐
1100 sponse/1,2 or check_response/2 to fetch the actual result of the
1101 request.
1102
1103 The call gen_statem:wait_response(gen_statem:send_re‐
1104 quest(ServerRef,Request), Timeout) can be seen as equivalent to
1105 gen_statem:call(Server,Request,Timeout), ignoring the error han‐
1106 dling.
1107
1108 The gen_statem calls the state callback with event_type()
1109 {call,From} and event content Request.
1110
1111 A Reply is generated when a state callback returns with {re‐
1112 ply,From,Reply} as one action(), and that Reply becomes the re‐
1113 turn value of wait_response/1,2 or check_response/2 function.
1114
1115 start(Module :: module(), Args :: term(), Opts :: [start_opt()]) ->
1116 start_ret()
1117
1118 start(ServerName :: server_name(),
1119 Module :: module(),
1120 Args :: term(),
1121 Opts :: [start_opt()]) ->
1122 start_ret()
1123
1124 Creates a standalone gen_statem process according to OTP design
1125 principles (using proc_lib primitives). As it does not get
1126 linked to the calling process, this start function cannot be
1127 used by a supervisor to start a child.
1128
1129 For a description of arguments and return values, see
1130 start_link/3,4.
1131
1132 start_link(Module :: module(),
1133 Args :: term(),
1134 Opts :: [start_opt()]) ->
1135 start_ret()
1136
1137 start_link(ServerName :: server_name(),
1138 Module :: module(),
1139 Args :: term(),
1140 Opts :: [start_opt()]) ->
1141 start_ret()
1142
1143 Creates a gen_statem process according to OTP design principles
1144 (using proc_lib primitives) that is linked to the calling
1145 process. This is essential when the gen_statem must be part of a
1146 supervision tree so it gets linked to its supervisor.
1147
1148 The gen_statem process calls Module:init/1 to initialize the
1149 server. To ensure a synchronized startup procedure,
1150 start_link/3,4 does not return until Module:init/1 has returned.
1151
1152 ServerName specifies the server_name() to register for the
1153 gen_statem. If the gen_statem is started with start_link/3, no
1154 ServerName is provided and the gen_statem is not registered.
1155
1156 Module is the name of the callback module.
1157
1158 Args is an arbitrary term that is passed as the argument to Mod‐
1159 ule:init/1.
1160
1161 * If option {timeout,Time} is present in Opts, the gen_statem
1162 is allowed to spend Time milliseconds initializing or it
1163 terminates and the start function returns {error,timeout}.
1164
1165 * If option {hibernate_after,HibernateAfterTimeout} is
1166 present, the gen_statem process awaits any message for Hi‐
1167 bernateAfterTimeout milliseconds and if no message is re‐
1168 ceived, the process goes into hibernation automatically (by
1169 calling proc_lib:hibernate/3).
1170
1171 * If option {debug,Dbgs} is present in Opts, debugging through
1172 sys is activated.
1173
1174 * If option {spawn_opt,SpawnOpts} is present in Opts,
1175 SpawnOpts is passed as option list to erlang:spawn_opt/2,
1176 which is used to spawn the gen_statem process.
1177
1178 Note:
1179 Using spawn option monitor is not allowed, it causes this func‐
1180 tion to fail with reason badarg.
1181
1182
1183 If the gen_statem is successfully created and initialized, this
1184 function returns {ok,Pid}, where Pid is the pid() of the
1185 gen_statem. If a process with the specified ServerName exists
1186 already, this function returns {error,{already_started,Pid}},
1187 where Pid is the pid() of that process.
1188
1189 If Module:init/1 fails with Reason, this function returns {er‐
1190 ror,Reason}. If Module:init/1 returns {stop,Reason} or ignore,
1191 the process is terminated and this function returns {error,Rea‐
1192 son} or ignore, respectively.
1193
1194 start_monitor(Module :: module(),
1195 Args :: term(),
1196 Opts :: [start_opt()]) ->
1197 start_mon_ret()
1198
1199 start_monitor(ServerName :: server_name(),
1200 Module :: module(),
1201 Args :: term(),
1202 Opts :: [start_opt()]) ->
1203 start_mon_ret()
1204
1205 Creates a standalone gen_statem process according to OTP design
1206 principles (using proc_lib primitives) and atomically sets up a
1207 monitor to the newly created process. As it does not get linked
1208 to the calling process, this start function cannot be used by a
1209 supervisor to start a child.
1210
1211 For a description of arguments and return values, see
1212 start_link/3,4. Note that the return value on successful start
1213 differs from start_link/3,4. start_monitor/3,4 will return
1214 {ok,{Pid,Mon}} where Pid is the process identifier of the
1215 process, and Mon is a reference to the monitor set up to monitor
1216 the process. If the start is not successful, the caller will be
1217 blocked until the DOWN message has been received and removed
1218 from the message queue.
1219
1220 stop(ServerRef :: server_ref()) -> ok
1221
1222 The same as stop(ServerRef, normal, infinity).
1223
1224 stop(ServerRef :: server_ref(),
1225 Reason :: term(),
1226 Timeout :: timeout()) ->
1227 ok
1228
1229 Orders the gen_statem ServerRef to exit with the specified Rea‐
1230 son and waits for it to terminate. The gen_statem calls Mod‐
1231 ule:terminate/3 before exiting.
1232
1233 This function returns ok if the server terminates with the ex‐
1234 pected reason. Any other reason than normal, shutdown, or {shut‐
1235 down,Term} causes an error report to be issued through log‐
1236 ger(3). The default Reason is normal.
1237
1238 Timeout is an integer > 0, which specifies how many milliseconds
1239 to wait for the server to terminate, or the atom infinity to
1240 wait indefinitely. Defaults to infinity. If the server does not
1241 terminate within the specified time, a timeout exception is
1242 raised.
1243
1244 If the process does not exist, a noproc exception is raised.
1245
1246 wait_response(RequestId :: request_id()) ->
1247 {reply, Reply :: term()} |
1248 {error, {term(), server_ref()}}
1249
1250 wait_response(RequestId :: request_id(), Timeout :: timeout()) ->
1251 {reply, Reply :: term()} |
1252 timeout |
1253 {error, {term(), server_ref()}}
1254
1255 This function is used to wait for a reply of a request made with
1256 send_request/2 from the gen_statem process. This function must
1257 be called from the same process from which send_request/2 was
1258 made.
1259
1260 Timeout is an integer greater then or equal to zero that speci‐
1261 fies how many milliseconds to wait for an reply, or the atom in‐
1262 finity to wait indefinitely. Defaults to infinity. If no reply
1263 is received within the specified time, the function returns
1264 timeout and no cleanup is done, and thus the function can be in‐
1265 voked repeatedly until a reply is returned.
1266
1267 The return value Reply is generated when a state callback re‐
1268 turns with {reply,From,Reply} as one action(), and that Reply
1269 becomes the return value of this function.
1270
1271 The function returns an error if the gen_statem dies before or
1272 during this function call.
1273
1275 The following functions are to be exported from a gen_statem callback
1276 module.
1277
1279 Module:callback_mode() -> CallbackMode
1280
1281 Types:
1282
1283 CallbackMode = callback_mode() | [ callback_mode() |
1284 state_enter() ]
1285
1286 This function is called by a gen_statem when it needs to find
1287 out the callback mode of the callback module. The value is
1288 cached by gen_statem for efficiency reasons, so this function is
1289 only called once after server start, after code change, and af‐
1290 ter changing the callback module, but before the first state
1291 callback in the current callback module's code version is
1292 called. More occasions may be added in future versions of
1293 gen_statem.
1294
1295 Server start happens either when Module:init/1 returns or when
1296 enter_loop/4-6 is called. Code change happens when Mod‐
1297 ule:code_change/4 returns. A change of the callback module hap‐
1298 pens when a state callback returns any of the actions
1299 change_callback_module, push_callback_module or pop_call‐
1300 back_module.
1301
1302 The CallbackMode is either just callback_mode() or a list con‐
1303 taining callback_mode() and possibly the atom state_enter.
1304
1305 Note:
1306 If this function's body does not return an inline constant value
1307 the callback module is doing something strange.
1308
1309
1310 Module:code_change(OldVsn, OldState, OldData, Extra) -> Result
1311
1312 Types:
1313
1314 OldVsn = Vsn | {down,Vsn}
1315 Vsn = term()
1316 OldState = NewState = term()
1317 Extra = term()
1318 Result = {ok,NewState,NewData} | Reason
1319 OldState = NewState = state()
1320 OldData = NewData = data()
1321 Reason = term()
1322
1323 Note:
1324 This callback is optional, so callback modules need not export
1325 it. If a release upgrade/downgrade with Change = {advanced,Ex‐
1326 tra} specified in the .appup file is made when code_change/4 is
1327 not implemented the process will crash with exit reason undef.
1328
1329
1330 This function is called by a gen_statem when it is to update its
1331 internal state during a release upgrade/downgrade, that is, when
1332 the instruction {update,Module,Change,...}, where Change = {ad‐
1333 vanced,Extra}, is specified in the appup file. For more informa‐
1334 tion, see OTP Design Principles.
1335
1336 For an upgrade, OldVsn is Vsn, and for a downgrade, OldVsn is
1337 {down,Vsn}. Vsn is defined by the vsn attribute(s) of the old
1338 version of the callback module Module. If no such attribute is
1339 defined, the version is the checksum of the Beam file.
1340
1341 OldState and OldData is the internal state of the gen_statem.
1342
1343 Extra is passed "as is" from the {advanced,Extra} part of the
1344 update instruction.
1345
1346 If successful, the function must return the updated internal
1347 state in an {ok,NewState,NewData} tuple.
1348
1349 If the function returns a failure Reason, the ongoing upgrade
1350 fails and rolls back to the old release. Note that Reason cannot
1351 be an {ok,_,_} tuple since that will be regarded as a {ok,New‐
1352 State,NewData} tuple, and that a tuple matching {ok,_} is an
1353 also invalid failure Reason. It is recommended to use an atom as
1354 Reason since it will be wrapped in an {error,Reason} tuple.
1355
1356 Also note when upgrading a gen_statem, this function and hence
1357 the Change = {advanced,Extra} parameter in the appup file is not
1358 only needed to update the internal state or to act on the Extra
1359 argument. It is also needed if an upgrade or downgrade should
1360 change callback mode, or else the callback mode after the code
1361 change will not be honoured, most probably causing a server
1362 crash.
1363
1364 If the server changes callback module using any of the actions
1365 change_callback_module, push_callback_module or pop_call‐
1366 back_module, be aware that it is always the current callback
1367 module that will get this callback call. That the current call‐
1368 back module handles the current state and data update should be
1369 no surprise, but it must be able to handle even parts of the
1370 state and data that it is not familiar with, somehow.
1371
1372 In the supervisor child specification there is a list of modules
1373 which is recommended to contain only the callback module. For a
1374 gen_statem with multiple callback modules there is no real need
1375 to list all of them, it may not even be possible since the list
1376 could change after code upgrade. If this list would contain only
1377 the start callback module, as recommended, what is important is
1378 to upgrade that module whenever a synchronized code replacement
1379 is done. Then the release handler concludes that an upgrade that
1380 upgrades that module needs to suspend, code change, and resume
1381 any server whose child specification declares that it is using
1382 that module. And again; the current callback module will get the
1383 Module:code_change/4 call.
1384
1385 Module:init(Args) -> Result(StateType)
1386
1387 Types:
1388
1389 Args = term()
1390 Result(StateType) = init_result(StateType)
1391
1392 Whenever a gen_statem is started using start_link/3,4,
1393 start_monitor/3,4, or start/3,4, this function is called by the
1394 new process to initialize the implementation state and server
1395 data.
1396
1397 Args is the Args argument provided to that start function.
1398
1399 Note:
1400 Note that if the gen_statem is started through proc_lib and en‐
1401 ter_loop/4-6, this callback will never be called. Since this
1402 callback is not optional it can in that case be implemented as:
1403
1404 init(Args) -> erlang:error(not_implemented, [Args]).
1405
1406
1407 Module:format_status(Opt, [PDict,State,Data]) -> Status
1408
1409 Types:
1410
1411 Opt = normal | terminate
1412 PDict = [{Key, Value}]
1413 State = state()
1414 Data = data()
1415 Key = term()
1416 Value = term()
1417 Status = term()
1418
1419 Note:
1420 This callback is optional, so a callback module does not need to
1421 export it. The gen_statem module provides a default implementa‐
1422 tion of this function that returns {State,Data}.
1423
1424 If this callback is exported but fails, to hide possibly sensi‐
1425 tive data, the default function will instead return
1426 {State,Info}, where Info says nothing but the fact that for‐
1427 mat_status/2 has crashed.
1428
1429
1430 This function is called by a gen_statem process when any of the
1431 following apply:
1432
1433 *
1434 One of sys:get_status/1,2 is invoked to get the gen_statem
1435 status. Opt is set to the atom normal for this case.
1436
1437 *
1438 The gen_statem terminates abnormally and logs an error. Opt
1439 is set to the atom terminate for this case.
1440
1441 This function is useful for changing the form and appearance of
1442 the gen_statem status for these cases. A callback module wishing
1443 to change the sys:get_status/1,2 return value and how its status
1444 appears in termination error logs exports an instance of for‐
1445 mat_status/2, which returns a term describing the current status
1446 of the gen_statem.
1447
1448 PDict is the current value of the process dictionary of the
1449 gen_statem.
1450
1451 State is the internal state of the gen_statem.
1452
1453 Data is the internal server data of the gen_statem.
1454
1455 The function is to return Status, a term that contains the ap‐
1456 propriate details of the current state and status of the
1457 gen_statem. There are no restrictions on the form Status can
1458 take, but for the sys:get_status/1,2 case (when Opt is normal),
1459 the recommended form for the Status value is [{data, [{"State",
1460 Term}]}], where Term provides relevant details of the gen_statem
1461 state. Following this recommendation is not required, but it
1462 makes the callback module status consistent with the rest of the
1463 sys:get_status/1,2 return value.
1464
1465 One use for this function is to return compact alternative state
1466 representations to avoid having large state terms printed in log
1467 files. Another use is to hide sensitive data from being written
1468 to the error log.
1469
1470 Module:StateName(enter, OldState, Data) -> StateEnterResult(StateName)
1471 Module:StateName(EventType, EventContent, Data) -> StateFunctionResult
1472 Module:handle_event(enter, OldState, State, Data) -> StateEnterRe‐
1473 sult(State)
1474 Module:handle_event(EventType, EventContent, State, Data) -> Han‐
1475 dleEventResult
1476
1477 Types:
1478
1479 EventType = event_type()
1480 EventContent = term()
1481 State = state()
1482 Data = NewData = data()
1483 StateEnterResult(StateName) = state_enter_result(StateName)
1484 StateFunctionResult = event_handler_result(state_name())
1485 StateEnterResult(State) = state_enter_result(State)
1486 HandleEventResult = event_handler_result(state())
1487
1488 Whenever a gen_statem receives an event from call/2, cast/2, or
1489 as a normal process message, one of these functions is called.
1490 If callback mode is state_functions, Module:StateName/3 is
1491 called, and if it is handle_event_function, Module:han‐
1492 dle_event/4 is called.
1493
1494 If EventType is {call,From}, the caller waits for a reply. The
1495 reply can be sent from this or from any other state callback by
1496 returning with {reply,From,Reply} in Actions, in Replies, or by
1497 calling reply(From, Reply).
1498
1499 If this function returns with a next state that does not match
1500 equal (=/=) to the current state, all postponed events are re‐
1501 tried in the next state.
1502
1503 The only difference between StateFunctionResult and HandleEven‐
1504 tResult is that for StateFunctionResult the next state must be
1505 an atom, but for HandleEventResult there is no restriction on
1506 the next state.
1507
1508 For options that can be set and actions that can be done by
1509 gen_statem after returning from this function, see action().
1510
1511 When the gen_statem runs with state enter calls, these functions
1512 are also called with arguments (enter, OldState, ...) during ev‐
1513 ery state change. In this case there are some restrictions on
1514 the actions that may be returned: postpone() is not allowed
1515 since a state enter call is not an event so there is no event to
1516 postpone, and {next_event,_,_} is not allowed since using state
1517 enter calls should not affect how events are consumed and pro‐
1518 duced. You may also not change states from this call. Should you
1519 return {next_state,NextState, ...} with NextState =/= State the
1520 gen_statem crashes. Note that it is actually allowed to use {re‐
1521 peat_state, NewData, ...} although it makes little sense since
1522 you immediately will be called again with a new state enter call
1523 making this just a weird way of looping, and there are better
1524 ways to loop in Erlang. If you do not update NewData and have
1525 some loop termination condition, or if you use {re‐
1526 peat_state_and_data, _} or repeat_state_and_data you have an in‐
1527 finite loop! You are advised to use {keep_state,...},
1528 {keep_state_and_data,_} or keep_state_and_data since changing
1529 states from a state enter call is not possible anyway.
1530
1531 Note the fact that you can use throw to return the result, which
1532 can be useful. For example to bail out with
1533 throw(keep_state_and_data) from deep within complex code that
1534 cannot return {next_state,State,Data} because State or Data is
1535 no longer in scope.
1536
1537 Module:terminate(Reason, State, Data) -> Ignored
1538
1539 Types:
1540
1541 Reason = normal | shutdown | {shutdown,term()} | term()
1542 State = state()
1543 Data = data()
1544 Ignored = term()
1545
1546 Note:
1547 This callback is optional, so callback modules need not export
1548 it. The gen_statem module provides a default implementation
1549 without cleanup.
1550
1551
1552 This function is called by a gen_statem when it is about to ter‐
1553 minate. It is to be the opposite of Module:init/1 and do any
1554 necessary cleaning up. When it returns, the gen_statem termi‐
1555 nates with Reason. The return value is ignored.
1556
1557 Reason is a term denoting the stop reason and State is the in‐
1558 ternal state of the gen_statem.
1559
1560 Reason depends on why the gen_statem is terminating. If it is
1561 because another callback function has returned, a stop tuple
1562 {stop,Reason} in Actions, Reason has the value specified in that
1563 tuple. If it is because of a failure, Reason is the error rea‐
1564 son.
1565
1566 If the gen_statem is part of a supervision tree and is ordered
1567 by its supervisor to terminate, this function is called with
1568 Reason = shutdown if both the following conditions apply:
1569
1570 * The gen_statem has been set to trap exit signals.
1571
1572 * The shutdown strategy as defined in the supervisor's child
1573 specification is an integer time-out value, not brutal_kill.
1574
1575 Even if the gen_statem is not part of a supervision tree, this
1576 function is called if it receives an 'EXIT' message from its
1577 parent. Reason is the same as in the 'EXIT' message.
1578
1579 Otherwise, the gen_statem is immediately terminated.
1580
1581 Notice that for any other reason than normal, shutdown, or
1582 {shutdown,Term}, the gen_statem is assumed to terminate because
1583 of an error and an error report is issued using logger(3).
1584
1586 gen_event(3), gen_fsm(3), gen_server(3), proc_lib(3), supervisor(3),
1587 sys(3).
1588
1589
1590
1591Ericsson AB stdlib 3.14.2.1 gen_statem(3)