Skip to content

Instantly share code, notes, and snippets.

@wjdix
Last active January 26, 2016 00:27
Show Gist options
  • Save wjdix/7bd2a09f929d47467530 to your computer and use it in GitHub Desktop.
Save wjdix/7bd2a09f929d47467530 to your computer and use it in GitHub Desktop.
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