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}readcountcoils.{:ri, slave, address, count}readcountinputs.{:rhr, slave, address, count}readcountholding registers.{:rir, slave, address, count}readcountinput 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:
transis the transport to use. Only the:tcptransport is available but other transports can be registered.protois the protocol to use. Available protocols are:tcpand: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.
ipis the internet address to connect to.portis the tcp port number to connect to.timeoutis 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}.