gen_fsm例子:code_lock

1832阅读 0评论2011-03-31 sunjiangang-ok
分类:LINUX

关键字: gen_fsm code_lock 改了一下代码,可以run了:


  1. %% code_lock.erl
  2. -module(code_lock).
  3. -behaviour(gen_fsm).
  4.   
  5. -export([start/1, button/1]).
  6. -export([locked/2, open/2]).
  7. -export([init/1, handle_event/3, handle_sync_event/4, handle_info/3, code_change/4, terminate/3]).
  8.   
  9. start(Code) ->
  10.   gen_fsm:start_link({local, code_lock}, code_lock, Code, []).
  11.   
  12. button(Digit) ->
  13.   gen_fsm:send_event(code_lock, {button, Digit}).
  14.   
  15. locked({button, Digit}, {SoFar, Code}) ->
  16.   io:format("Now the code you input is: ~w~n", [SoFar ++ [Digit]]),
  17.   case SoFar ++ [Digit] of
  18.     Code ->
  19.       io:format("Open!~n"),
  20.       {next_state, open, {[], Code}, 3000};
  21.     Incomplete when length(Incomplete) < length(Code) ->
  22.       {next_state, locked, {Incomplete, Code}};
  23.     _Wrong ->
  24.       io:format("Wrong Code! Start Again!~n"),
  25.       {next_state, locked, {[], Code}}
  26.   end.
  27.   
  28. open(timeout, State) ->
  29.   io:format("Lock!~n"),
  30.   {next_state, locked, State}.
  31.   
  32. init(Code) ->
  33.   {ok, locked, {[], Code}}.
  34.   
  35. handle_event(_A, _B, _C) ->
  36.   {next_state, ok, ok}.
  37.   
  38. handle_sync_event(_A, _B, _C, _D) ->
  39.   {reply, ok, ok, ok}.
  40.   
  41. handle_info(_A, _B, _C) ->
  42.   {next_state, ok, ok}.
  43.   
  44. code_change(_A, _B, _C, _D) ->
  45.   {ok, ok, ok}.
  46.   
  47. terminate(_A, _B, _C) ->
  48.   ok.

编译运行:

  1. D:\erl\code>erl
  2. Eshell V5.6.3 (abort with ^G)
  3. 1> c(code_lock).
  4. {ok,code_lock}
  5. 2> code_lock:start([1,2,3]).
  6. {ok,<0.36.0>}
  7. 3> code_lock:button(1).
  8. Now the code you input is: [1]
  9. ok
  10. 4> code_lock:button(2).
  11. Now the code you input is: [1,2]
  12. ok
  13. 5> code_lock:button(3).
  14. Now the code you input is: [1,2,3]
  15. ok
  16.   
  17. 6>
  18. 6> code_lock:button(1).
  19. Now the code you input is: [1]
  20. ok
  21. 7> code_lock:button(2).
  22. Now the code you input is: [1,2]
  23. ok
  24. 8> code_lock:button(2).
  25. Now the code you input is: [1,2,2]
  26. ok
  27. Wrong Start
  28. 9>
上一篇:erlang客户端程序学习(三)
下一篇:牛刀小试--删除多余的lrc文件