-
Notifications
You must be signed in to change notification settings - Fork 9
/
supervisor.ex
67 lines (57 loc) · 1.98 KB
/
supervisor.ex
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
defmodule Grizzly.Connections.Supervisor do
@moduledoc false
use DynamicSupervisor
alias Grizzly.{Connection, Options, ZWave}
alias Grizzly.Connections.{AsyncConnection, BinaryConnection, SyncConnection}
@spec start_link(Options.t()) :: Supervisor.on_start()
def start_link(options) do
DynamicSupervisor.start_link(__MODULE__, options, name: __MODULE__)
end
@doc """
Start a connection to a Z-Wave Node or the Z/IP Gateway
"""
@spec start_connection(ZWave.node_id() | :gateway, [Connection.opt()]) ::
{:ok, pid()} | {:error, :timeout}
def start_connection(node_id, opts \\ []) do
case Keyword.get(opts, :mode, :sync) do
:async ->
# put the calling process as the owner if sine the supervisor
# will be owner when calling form here.
opts = Keyword.put_new(opts, :owner, self())
do_start_connection(AsyncConnection, node_id, opts)
:sync ->
do_start_connection(SyncConnection, node_id)
:binary ->
do_start_connection(BinaryConnection, node_id, owner: self())
end
end
@doc """
Close all the connections
"""
@spec close_all_connections() :: :ok
def close_all_connections() do
if GenServer.whereis(__MODULE__) != nil do
connections_pids = DynamicSupervisor.which_children(__MODULE__)
Enum.each(connections_pids, fn {_, connection_pid, _, _} ->
:ok = Connection.close(connection_pid)
end)
end
:ok
catch
:exit, {:noproc, _} -> :ok
end
@impl DynamicSupervisor
def init(grizzly_options) do
DynamicSupervisor.init(strategy: :one_for_one, extra_arguments: [grizzly_options])
end
defp do_start_connection(connection_module, node_id, command_opts \\ []) do
case DynamicSupervisor.start_child(
__MODULE__,
connection_module.child_spec(node_id, command_opts)
) do
{:ok, _} = ok -> ok
{:error, {:already_started, pid}} -> {:ok, pid}
{:error, _reason} = other_error -> other_error
end
end
end