There is an locked door example about gen_fsm in the Elrang Otp System Documentation. I have a question about timeout. I will copy the code here first:
-module(code_lock).
-behaviour(gen_fsm).
-export([start_link/1]).
-export([button/1]).
-export([init/1, locked/2, open/2]).
start_link(Code) ->
gen_fsm:start_link({local, code_lock}, code_lock, lists:reverse(Code), []).
button(Digit) ->
gen_fsm:send_event(code_lock, {button, Digit}).
init(Code) ->
{ok, locked, {[], Code}}.
locked({button, Digit}, {SoFar, Code}) ->
case [Digit|SoFar] of
Code ->
do_unlock(),
{next_state, open, {[], Code}, 30000};
Incomplete when length(Incomplete)<length(Code) ->
{next_state, locked, {Incomplete, Code}};
_Wrong ->
{next_state, locked, {[], Code}}
end.
open(timeout, State) ->
do_lock(),
{next_state, locked, State}.
Here is the question: when the door is opened, if I press the button, the gen_fsm will have an {button, Digit} event at the state open. An error will occurs. But if I add these code after open function:
open(_Event, State) ->
{next_state, open, State}.
Then if I press the button in 30s, the timeout will not be occurs. The door will be opened forever. What should I do?
Thanks.
Update:
I know I could use send_event_after or something like that. But I don't think it is a good idea. Because the state you excepted to handle the message may be changed in a complex application.
For example, if I have a function to lock the door manually after the door opened in 30s. Then locked will handle the timeout message, which is not the excepted behaviour.
You should be specifying a timeout at the open function "open(_Event, State)"
Since the next state is proceeded without timeout.. the door will remain open forever and no where a timeout occurs..
The newly defined function should be
open(_Event, State) -> {next_state, open, State, 30000}. %% State should be re-initialized