Modbus.Tcp.Master (modbus v0.3.9)

TCP Master server.

Example

# run with: mix slave
alias Modbus.Tcp.Slave
alias Modbus.Tcp.Master

# start your slave with a shared model
model = %{0x50 => %{{:c, 0x5152} => 0}}
{:ok, spid} = Slave.start_link(model: model)
# get the assigned tcp port
port = Slave.port(spid)

# interact with it through the master
{:ok, mpid} = Master.start_link(ip: {127, 0, 0, 1}, port: port)
:ok = Master.exec(mpid, {:fc, 0x50, 0x5152, 0})
{:ok, [0]} = Master.exec(mpid, {:rc, 0x50, 0x5152, 1})
:ok = Master.exec(mpid, {:fc, 0x50, 0x5152, 1})
{:ok, [1]} = Master.exec(mpid, {:rc, 0x50, 0x5152, 1})

Link to this section Summary

Functions

Executes a Modbus command.

Opens the connection.

Closes the connection.

Link to this section Functions

Link to this function

exec(pid, cmd, timeout \\ 2000)

Executes a Modbus command.

cmd is one of:

  • {:rc, slave, address, count} read count coils.
  • {:ri, slave, address, count} read count inputs.
  • {:rhr, slave, address, count} read count holding registers.
  • {:rir, slave, address, count} read count input registers.
  • {:fc, slave, address, value} force single coil.
  • {:phr, slave, address, value} preset single holding register.
  • {:fc, slave, address, values} force multiple coils.
  • {:phr, slave, address, values} preset multiple holding registers.

Returns :ok | {:ok, [values]} | {:error, reason}.

Link to this function

start_link(opts)

Opens the connection.

opts is a keyword list where:

  • ip is the internet address to connect to.
  • port is the tcp port number to connect to.
  • timeout is the optional connection timeout.

Returns {:ok, pid} | {:error, reason}.

Example

Modbus.Tcp.Master.start_link(ip: {10,77,0,10}, port: 502, timeout: 2000)

Closes the connection.