Modbus.Master (modbus v0.4.0)
Modbus Master.
Example
# run with: mix slave
alias Modbus.Slave
alias Modbus.Master
# start your slave with a shared model
model = %{
0x50 => %{
{:c, 0x5152} => 0,
{:i, 0x5354} => 0,
{:i, 0x5355} => 1,
{:hr, 0x5657} => 0x6162,
{:ir, 0x5859} => 0x6364,
{:ir, 0x585A} => 0x6566
}
}
{:ok, slave} = Slave.start_link(model: model)
# get the assigned tcp port
port = Slave.port(slave)
# interact with it
{:ok, master} = Master.start_link(ip: {127, 0, 0, 1}, port: port)
# read input
{:ok, [0, 1]} = Master.exec(master, {:ri, 0x50, 0x5354, 2})
# read input registers
{:ok, [0x6364, 0x6566]} = Master.exec(master, {:rir, 0x50, 0x5859, 2})
# toggle coil and read it back
:ok = Master.exec(master, {:fc, 0x50, 0x5152, 0})
{:ok, [0]} = Master.exec(master, {:rc, 0x50, 0x5152, 1})
:ok = Master.exec(master, {:fc, 0x50, 0x5152, 1})
{:ok, [1]} = Master.exec(master, {:rc, 0x50, 0x5152, 1})
# increment holding register and read it back
{:ok, [0x6162]} = Master.exec(master, {:rhr, 0x50, 0x5657, 1})
:ok = Master.exec(master, {:phr, 0x50, 0x5657, 0x6163})
{:ok, [0x6163]} = Master.exec(master, {:rhr, 0x50, 0x5657, 1})
:ok = Master.stop(master)
:ok = Slave.stop(slave)
Link to this section Summary
Link to this section Functions
Link to this function
exec(master, cmd, timeout \\ 2000)
Executes a Modbus command.
cmd
is one of:
{:rc, slave, address, count}
readcount
coils.{:ri, slave, address, count}
readcount
inputs.{:rhr, slave, address, count}
readcount
holding registers.{:rir, slave, address, count}
readcount
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:
trans
is the transport to use. Only the:tcp
transport is available but other transports can be registered.proto
is the protocol to use. Available protocols are:tcp
and:rtu
. Defaults to:tcp
.
The rest of options are passed verbatim to the transport constructor.
The following are the options needed by the default TCP transport.
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, master}
| {:error, reason}
.
Example
Modbus.Master.start_link(ip: {10,77,0,10}, port: 502, timeout: 2000)
Link to this function
stop(master)
Closes the connection.
Returns :ok
| {:error, reason}
.