Last active
January 26, 2016 00:27
-
-
Save wjdix/7bd2a09f929d47467530 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
defmodule Switch do | |
def start_link(n \\ 10, callback \\ fn (_) -> IO.puts "Turned on" end, opts \\ []) do | |
:gen_fsm.start_link(__MODULE__, [n, callback], opts) | |
end | |
def init([n, callback]) do | |
{:ok, :off, %{n: n, received: 0, on_callback: callback}} | |
end | |
def off({:event}, state) do | |
if state.received + 1 > state.n do | |
{:next_state, :on, %{state | received: state.received + 1}} | |
else | |
{:next_state, :off, %{state | received: state.received + 1}} | |
end | |
end | |
def on(_, state) do | |
state.on_callback() | |
{:next_state, :on, state} | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment