Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions lib/tcp/client.ex
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,13 @@ defmodule Modbux.Tcp.Client do
GenServer.call(pid, :flush)
end

@doc """
Determine if the Client is connected to a Server.
"""
def connected?(pid) do
GenServer.call(pid, :connected?)
end

# callbacks
def init(args) do
port = args[:tcp_port] || @port
Expand Down Expand Up @@ -311,6 +318,11 @@ defmodule Modbux.Tcp.Client do
{:reply, {:ok, state.pending_msg}, new_state}
end

def handle_call(:connected?, _from, state) do
connected? = state.socket != nil && state.status == :connected
{:reply, connected?, state}
end

# only for active mode (active: true)
def handle_info({:tcp, _port, response}, state) do
Logger.debug("(#{__MODULE__}, :message_active) response: #{inspect(response)}")
Expand Down
11 changes: 11 additions & 0 deletions test/tcp/modbus_tcp_client_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -19,4 +19,15 @@ defmodule ModbuxTcpClientTest do
assert {:error, :econnrefused} == Client.connect(cpid)
assert {:error, :closed} == Client.close(cpid)
end

test "test Client connectivity status" do
{:ok, _spid} = Server.start_link(model: %{}, port: 2000)
{:ok, cpid} = Client.start_link(ip: {127, 0, 0, 1}, tcp_port: 2000)
assert false == Client.connected?(cpid)
assert :ok == Client.connect(cpid)
assert true == Client.connected?(cpid)
assert :ok == Client.close(cpid)
assert false == Client.connected?(cpid)
assert :ok == Client.stop(cpid)
end
end