From 6a5a9eece73fae884663d80fe5eabaf139d4f1ee Mon Sep 17 00:00:00 2001 From: Pim Kunis Date: Thu, 25 Jul 2019 14:58:11 +0200 Subject: [PATCH] Test if GPIO is alive using Process.alive?/1 instead of using GenServer's state. Fix signal sending twice because of copy-paste error. --- morse/lib/morse_server.ex | 21 +++++++++------------ morse/lib/morse_signaler.ex | 7 ++----- 2 files changed, 11 insertions(+), 17 deletions(-) diff --git a/morse/lib/morse_server.ex b/morse/lib/morse_server.ex index 25f207b..ab17dfb 100644 --- a/morse/lib/morse_server.ex +++ b/morse/lib/morse_server.ex @@ -8,7 +8,7 @@ defmodule MorseServer do end def start_link do - GenServer.start_link(__MODULE__, :off, name: __MODULE__) + GenServer.start_link(__MODULE__, nil, name: __MODULE__) end def start_morse do @@ -21,17 +21,14 @@ defmodule MorseServer do end @impl true - def handle_call(:start, _from, :on) do - {:reply, {:error, :already_started}, :on} - end + def handle_call(:start, _from, pid) do + cond do + pid == nil or not Process.alive?(pid) -> + pid = spawn(&MorseSignaler.signal/0) + {:reply, :ok, pid} - def handle_call(:start, _from, :off) do - spawn(MorseSignaler, :signal, [self()]) - {:reply, :ok, :on} - end - - @impl true - def handle_cast(:done, :on) do - {:noreply, :off} + true -> + {:reply, {:error, :already_started}, pid} + end end end diff --git a/morse/lib/morse_signaler.ex b/morse/lib/morse_signaler.ex index 0137773..fda9260 100644 --- a/morse/lib/morse_signaler.ex +++ b/morse/lib/morse_signaler.ex @@ -19,14 +19,11 @@ defmodule MorseSignaler do Notifies the parent when the signalling is done. """ - def signal(server_pid) do + def signal() do {:ok, gpio} = GPIO.open(relay_pin(), :output) GPIO.write(gpio, @off) Process.sleep(@sleep_start) signal_sentence(gpio, String.graphemes(secret_code())) - - GenServer.cast(server_pid, :done) - :ok end # Signal a whole sentence of symbols with GPIO. @@ -65,6 +62,6 @@ defmodule MorseSignaler do end defp secret_code do - signal(Application.fetch_env!(:morse, :morse_message)) + Application.fetch_env!(:morse, :morse_message) end end