Test if GPIO is alive using Process.alive?/1 instead of using

GenServer's state.
Fix signal sending twice because of copy-paste error.
This commit is contained in:
Pim Kunis 2019-07-25 14:58:11 +02:00
parent b6b684af25
commit 6a5a9eece7
2 changed files with 11 additions and 17 deletions

View file

@ -8,7 +8,7 @@ defmodule MorseServer do
end end
def start_link do def start_link do
GenServer.start_link(__MODULE__, :off, name: __MODULE__) GenServer.start_link(__MODULE__, nil, name: __MODULE__)
end end
def start_morse do def start_morse do
@ -21,17 +21,14 @@ defmodule MorseServer do
end end
@impl true @impl true
def handle_call(:start, _from, :on) do def handle_call(:start, _from, pid) do
{:reply, {:error, :already_started}, :on} cond do
end pid == nil or not Process.alive?(pid) ->
pid = spawn(&MorseSignaler.signal/0)
{:reply, :ok, pid}
def handle_call(:start, _from, :off) do true ->
spawn(MorseSignaler, :signal, [self()]) {:reply, {:error, :already_started}, pid}
{:reply, :ok, :on}
end end
@impl true
def handle_cast(:done, :on) do
{:noreply, :off}
end end
end end

View file

@ -19,14 +19,11 @@ defmodule MorseSignaler do
Notifies the parent when the signalling is done. Notifies the parent when the signalling is done.
""" """
def signal(server_pid) do def signal() do
{:ok, gpio} = GPIO.open(relay_pin(), :output) {:ok, gpio} = GPIO.open(relay_pin(), :output)
GPIO.write(gpio, @off) GPIO.write(gpio, @off)
Process.sleep(@sleep_start) Process.sleep(@sleep_start)
signal_sentence(gpio, String.graphemes(secret_code())) signal_sentence(gpio, String.graphemes(secret_code()))
GenServer.cast(server_pid, :done)
:ok
end end
# Signal a whole sentence of symbols with GPIO. # Signal a whole sentence of symbols with GPIO.
@ -65,6 +62,6 @@ defmodule MorseSignaler do
end end
defp secret_code do defp secret_code do
signal(Application.fetch_env!(:morse, :morse_message)) Application.fetch_env!(:morse, :morse_message)
end end
end end