2019-07-24 21:56:42 +00:00
|
|
|
defmodule MorseServer do
|
|
|
|
use GenServer
|
|
|
|
use Application
|
|
|
|
|
|
|
|
@impl true
|
|
|
|
def start(_type, _args) do
|
|
|
|
start_link()
|
|
|
|
end
|
|
|
|
|
|
|
|
def start_link do
|
2019-07-30 22:20:09 +00:00
|
|
|
GenServer.start_link(__MODULE__, {nil, 0}, name: __MODULE__)
|
2019-07-24 21:56:42 +00:00
|
|
|
end
|
|
|
|
|
|
|
|
def start_morse do
|
|
|
|
GenServer.call(__MODULE__, :start)
|
|
|
|
end
|
|
|
|
|
2019-07-30 22:20:09 +00:00
|
|
|
def update_progress(progress) do
|
|
|
|
GenServer.cast(__MODULE__, {:progress, progress})
|
|
|
|
end
|
|
|
|
|
2019-07-24 21:56:42 +00:00
|
|
|
@impl true
|
|
|
|
def init(state) do
|
|
|
|
{:ok, state}
|
|
|
|
end
|
|
|
|
|
|
|
|
@impl true
|
2019-07-30 22:20:09 +00:00
|
|
|
def handle_call(:start, _from, {pid, _progress} = state) do
|
2019-07-25 12:58:11 +00:00
|
|
|
cond do
|
|
|
|
pid == nil or not Process.alive?(pid) ->
|
|
|
|
pid = spawn(&MorseSignaler.signal/0)
|
2019-07-30 22:20:09 +00:00
|
|
|
{:reply, :ok, {pid, 0}}
|
2019-07-24 21:56:42 +00:00
|
|
|
|
2019-07-25 12:58:11 +00:00
|
|
|
true ->
|
2019-07-30 22:20:09 +00:00
|
|
|
{:reply, {:error, :already_started}, state}
|
2019-07-25 12:58:11 +00:00
|
|
|
end
|
2019-07-24 21:56:42 +00:00
|
|
|
end
|
2019-07-30 22:20:09 +00:00
|
|
|
|
|
|
|
@impl true
|
2019-07-31 12:24:51 +00:00
|
|
|
def handle_cast({:progress, new_progress}, {pid, _progress}) do
|
2019-07-30 22:20:09 +00:00
|
|
|
broadcast_progress(new_progress)
|
|
|
|
{:noreply, {pid, new_progress}}
|
|
|
|
end
|
|
|
|
|
|
|
|
defp broadcast_progress(progress) do
|
|
|
|
UiWeb.Endpoint.broadcast("morse:progress", "update", %{value: progress})
|
|
|
|
end
|
2019-07-24 21:56:42 +00:00
|
|
|
end
|