modbuspp  1.1.40
C++ wrapper for the libmodbus library
Modbus::Master Class Reference

Master connected to Modbus (Client) More...

#include <master.h>

Inheritance diagram for Modbus::Master:
Inheritance graph

Public Member Functions

SlaveaddSlave (int slaveAddr)
 Adds a slave. More...
 
NetLayerbackend () const
 underlying backend
 
double byteTimeout ()
 Get timeout between bytes. More...
 
bool byteTimeout (Timeout &timeout)
 Get timeout between bytes. More...
 
virtual void close ()
 Close a Modbus connection.
 
std::string connection () const
 Returns the connection used. More...
 
bool debug () const
 Return the debug flag.
 
int flush ()
 Flush non-transmitted data. More...
 
bool hasSlave (int slaveAddr) const
 Check if the slave at the given address slaveAddrexists.
 
double indicationTimeout ()
 Get timeout used to wait for an indication (request received by a server) More...
 
bool indicationTimeout (Timeout &timeout)
 Get timeout used to wait for an indication (request received by a server) More...
 
bool isConnected () const
 Returns true if the device is connected; otherwise returns false. More...
 
virtual bool isOpen () const
 Returns true if the device is open; otherwise returns false. More...
 
bool isValid () const
 returns true if backend is set
 
 Master (Net net, const std::string &connection, const std::string &settings)
 
 Master (const std::string &jsonfile, const std::string &key=std::string())
 constructor from a JSON file More...
 
 Master ()
 Default constructor. More...
 
Net net () const
 Underlying layer used (backend) More...
 
virtual bool open ()
 Establish a Modbus connection. More...
 
Slaveoperator[] (int)
 Slave table access operator. More...
 
const Slaveoperator[] (int) const
 
int receiveResponse (uint8_t *rsp)
 Receive a confirmation request. More...
 
int receiveResponse (Message &rsp)
 
bool recoveryLink () const
 Returns true if link recovery mode is set; otherwise returns false.
 
double responseTimeout ()
 Get timeout for response. More...
 
bool responseTimeout (Timeout &timeout)
 Get timeout for response. More...
 
RtuLayerrtu ()
 underlying RTU layer (backend) More...
 
int sendRawMessage (Message *msg, bool prepareBefore=false)
 Send a request/response msg via the socket of the context() More...
 
int sendRawMessage (Message &msg, bool prepareBefore=false)
 
int sendRawRequest (const uint8_t *req, size_t len)
 Send a raw request. More...
 
int sendRawRequest (const Message &req)
 
bool setBackend (Net net, const std::string &connection, const std::string &setting)
 Sets the backend for the net network. More...
 
bool setByteTimeout (const double &timeout)
 Set timeout between bytes. More...
 
bool setByteTimeout (const Timeout &timeout)
 Set timeout between bytes. More...
 
bool setConfig (const std::string &jsonfile, const std::string &key=std::string())
 Set configuration from a JSON file. More...
 
bool setDebug (bool debug=true)
 Set debug flag. More...
 
bool setIndicationTimeout (const double &timeout)
 Set timeout for indication. More...
 
bool setIndicationTimeout (const Timeout &timeout)
 Set timeout for indication. More...
 
bool setRecoveryLink (bool recovery=true)
 
bool setResponseTimeout (const double &timeout)
 Set timeout for response. More...
 
bool setResponseTimeout (const Timeout &timeout)
 Set timeout for response. More...
 
std::string settings () const
 Returns the connection settings. More...
 
Slaveslave (int slaveAddr=-1)
 Returns the slave whose address is provided. More...
 
const Slaveslave (int slaveAddr=-1) const
 
SlaveslavePtr (int slaveAddr=-1)
 Returns a pointer to the slave whose address is provided. More...
 
const SlaveslavePtr (int slaveAddr=-1) const
 
const std::map< int, std::shared_ptr< Slave > > & slaves () const
 Returns the list of slaves as a map indexed by identifier number.
 
TcpLayertcp ()
 underlying TCP layer (backend) More...
 
virtual ~Master ()
 Destructor. More...
 

Static Public Member Functions

static std::string lastError ()
 last error message More...
 

Detailed Description

Master connected to Modbus (Client)

The Modbus master is the only one able to initiate a transaction with the slaves. This class therefore makes it possible to read or write in Modbus slaves.

To use, simply perform the following actions:

// instantiate a variable by choosing the network and the parameters to connect to it
Master mb (Rtu, port , "38400E1");
// adds a new slave and gets her reference
Slave & slave = mb.addSlave(33);
// open the communication
mb.open ();
// perform read or write operations for this slave
slave.readInputRegisters (1, values, 2);
Examples:
master/read-coils/main.cpp, master/read-holding-data/main.cpp, master/read-input-registers/main.cpp, master/report-slave-id/main.cpp, master/rw-holding-json/main.cpp, master/write-holding-data/main.cpp, and router/router-simple/main.cpp.

Constructor & Destructor Documentation

◆ Master() [1/3]

Modbus::Master::Master ( Net  net,
const std::string &  connection,
const std::string &  settings 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ Master() [2/3]

Modbus::Master::Master ( const std::string &  jsonfile,
const std::string &  key = std::string() 
)
explicit

constructor from a JSON file

The file describes the configuration to apply, its format is as follows:

{
"modbuspp-master": {
"mode": "rtu",
"connection": "/dev/ttyS1",
"settings": "38400E1",
"debug": true,
"response-timeout": 500,
"byte-timeout": 500,
"rtu": {
"mode": "rs485",
"rts": "down"
},
"slaves": [
{
"id": 33,
"pdu-adressing": false
},
{
"id": 34,
"pdu-adressing": true
}
]
}
}

Only the first 3 elements are mandatory : mode, connection and settings, the others are optional. In this example "modbuspp-master" is the key to the JSON object that should be used. If the key provided is empty, the file contains only one object corresponding to the configuration.

For slave objects, only the id field is required.

Parameters
keyname of the object key in the JSON file corresponding to the configuration to be applied
jsonfileJSON file path

◆ Master() [3/3]

Modbus::Master::Master ( )

Default constructor.

object cannot be used without calling setBackend() or setConfig()

◆ ~Master()

virtual Modbus::Master::~Master ( )
virtual

Destructor.

The destructor closes the connection if it is open and releases all affected resources.

Member Function Documentation

◆ addSlave()

Slave& Modbus::Master::addSlave ( int  slaveAddr)

Adds a slave.

This function shall add a slave with the slaveAddr value.

The behavior depends of network and the role of the device:

  • RTU: Define the slave ID of the remote device to talk in master mode or set the internal slave ID in slave mode. According to the protocol, a Modbus device must only accept message holding its slave number or the special broadcast number.
  • TCP: The slave number is only required in TCP if the message must reach a device on a serial link. Some not compliant devices or software (such as modpoll) uses the slave ID as unit identifier, that's incorrect (cf page 23 of Modbus Messaging Implementation Guide v1.0b) but without the slave value, the faulty remote device or software drops the requests !

    The special value TcpSlave (255) can be used in TCP mode to restore the default value.

Returns
the slave by reference
See also
slave()
Examples:
master/read-coils/main.cpp, master/read-holding-data/main.cpp, master/read-input-registers/main.cpp, master/report-slave-id/main.cpp, and master/write-holding-data/main.cpp.

◆ byteTimeout() [1/2]

double Modbus::Device::byteTimeout ( )
inherited

Get timeout between bytes.

Returns
timeout between bytes in seconds.
See also
setByteTimeout()

◆ byteTimeout() [2/2]

bool Modbus::Device::byteTimeout ( Timeout timeout)
inherited

Get timeout between bytes.

This function shall store the timeout interval between two consecutive bytes of the same message in the timeout argument.

Parameters
timeoutreference on the variable that will contain the timeout value
Returns
true if successful.
See also
setByteTimeout()

◆ connection()

std::string Modbus::Device::connection ( ) const
inherited

Returns the connection used.

Serial port or host depending on the backend.

For the Tcp backend :

  • connection specifies the host name or IP address of the host to connect to, eg. "192.168.0.5" , "::1" or "server.com".

For the Rtu backend :

  • connection specifies the name of the serial port handled by the OS, eg. "/dev/ttyS0" or "/dev/ttyUSB0",
Examples:
master/read-coils/main.cpp, master/read-holding-data/main.cpp, master/read-input-registers/main.cpp, master/report-slave-id/main.cpp, master/rw-holding-json/main.cpp, master/write-holding-data/main.cpp, router/router-json/main.cpp, router/router-simple/main.cpp, server/callback-server-json/main.cpp, server/clock-server-json/main.cpp, server/clock-server/main.cpp, and server/simple-server-json/main.cpp.

◆ flush()

int Modbus::Device::flush ( )
inherited

Flush non-transmitted data.

This function shall discard data received but not read to the socket or file descriptor associated to this connection.

Returns
0 or the number of flushed bytes if successful. Otherwise it shall return -1 and set errno.

◆ indicationTimeout() [1/2]

double Modbus::Device::indicationTimeout ( )
inherited

Get timeout used to wait for an indication (request received by a server)

This function shall return the timeout interval used to wait for an indication in timeout. Indication is the term used by the Modbus protocol to designate a request received by the server.

The default value is zero, it means the server will wait forever.

Returns
timeout for indication in seconds.
See also
setIndicationTimeout()

◆ indicationTimeout() [2/2]

bool Modbus::Device::indicationTimeout ( Timeout timeout)
inherited

Get timeout used to wait for an indication (request received by a server)

This function shall return the timeout interval used to wait for an indication in timeout. Indication is the term used by the Modbus protocol to designate a request received by the server.

The default value is zero, it means the server will wait forever.

Parameters
timeoutreference on the variable that will contain the timeout value
Returns
true if successful.
See also
setIndicationTimeout()

◆ isConnected()

bool Modbus::Device::isConnected ( ) const
inherited

Returns true if the device is connected; otherwise returns false.

in RTU mode, this function returns the same value as isOpen().

in TCP mode, this function returns true if a peer-to-peer TCP connection is currently established. Indeed, in server mode (slave), calling the open() function puts the Device in passive waiting mode, so that it is open but not connected. It is when a client connects that the function returns true.

See also
isOpen()

◆ isOpen()

virtual bool Modbus::Device::isOpen ( ) const
virtualinherited

◆ lastError()

static std::string Modbus::Device::lastError ( )
staticinherited

last error message

This function shall return the error message corresponding to the last error. This function must be called right after the instruction that triggered an error.

Examples:
master/read-coils/main.cpp, master/read-holding-data/main.cpp, master/read-input-registers/main.cpp, master/report-slave-id/main.cpp, master/rw-holding-json/main.cpp, and master/write-holding-data/main.cpp.

◆ net()

Net Modbus::Device::net ( ) const
inherited

Underlying layer used (backend)

This function allows to know the underlying layer used.

◆ open()

virtual bool Modbus::Device::open ( )
virtualinherited

◆ operator[]() [1/2]

Slave& Modbus::Master::operator[] ( int  )

Slave table access operator.

master being an object of class Master, master[i] is equivalent to master.slave(i)

◆ operator[]() [2/2]

const Slave& Modbus::Master::operator[] ( int  ) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ receiveResponse() [1/2]

int Modbus::Master::receiveResponse ( uint8_t *  rsp)

Receive a confirmation request.

This function shall receive a request confirmation. This function must be used for debugging purposes because the received response isn't checked against the initial request. This function can be used to receive request not handled by the library.

Returns
The function shall store the confirmation request in rsp and return the response length if sucessful. Otherwise it shall return -1 and set errno.

◆ receiveResponse() [2/2]

int Modbus::Master::receiveResponse ( Message rsp)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ responseTimeout() [1/2]

double Modbus::Device::responseTimeout ( )
inherited

Get timeout for response.

Returns
timeout for response in seconds.
See also
setResponseTimeout()

◆ responseTimeout() [2/2]

bool Modbus::Device::responseTimeout ( Timeout timeout)
inherited

Get timeout for response.

This function shall return the timeout interval used to wait for a response in the timeout argument.

Parameters
timeoutreference on the variable that will contain the timeout value
Returns
true if successful.
See also
setResponseTimeout()

◆ rtu()

RtuLayer& Modbus::Device::rtu ( )
inherited

underlying RTU layer (backend)

This function shall return the RTU layer if it is the layer used by the device. If it does not, a std::domain_error exception is thrown.

Examples:
router/router-simple/main.cpp.

◆ sendRawMessage() [1/2]

int Modbus::Device::sendRawMessage ( Message msg,
bool  prepareBefore = false 
)
inherited

Send a request/response msg via the socket of the context()

This function can be used to send message not handled by the library. The message is transmitted "raw", without any modification if prepareBefore is false, otherwise the message is modified to add a header (for TCP-IP) or a CRC (for RTU).

Returns
The function shall return the full message length, if successful. Otherwise it shall return -1 and set errno
Warning
This function is not supported in RTU mode on Windows™.
Examples:
server/callback-server-json/main.cpp.

◆ sendRawMessage() [2/2]

int Modbus::Device::sendRawMessage ( Message msg,
bool  prepareBefore = false 
)
inherited

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ sendRawRequest() [1/2]

int Modbus::Master::sendRawRequest ( const uint8_t *  req,
size_t  len 
)

Send a raw request.

This function shall send a request. This function must be used for debugging purposes because you have to take care to make a valid request by hand. The function only adds to the message, the header or CRC of the selected backend, so req must start and contain at least a slave/unit identifier and a function code. This function can be used to send request not handled by the library.

Returns
The function shall return the full message length, counting the extra data relating to the backend, if successful. Otherwise it shall return -1 and set errno.

◆ sendRawRequest() [2/2]

int Modbus::Master::sendRawRequest ( const Message req)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ setBackend()

bool Modbus::Device::setBackend ( Net  net,
const std::string &  connection,
const std::string &  setting 
)
inherited

Sets the backend for the net network.

This function does nothing if isValid() is true and returns false.

For the Tcp backend :

  • connection specifies the host name or IP address of the host to connect to, eg. "192.168.0.5" , "::1" or "server.com". "*" value can be used to listen any addresses in server mode,
  • settings is the service name/port number to connect to. To use the default Modbus port use the string "502". On many Unix systems, it’s convenient to use a port number greater than or equal to 1024 because it’s not necessary to have administrator privileges.

For the Rtu backend :

  • connection specifies the name of the serial port handled by the OS, eg. "/dev/ttyS0" or "/dev/ttyUSB0",
  • settings specifies communication settings as a string in the format BBBBPS. BBBB specifies the baud rate of the communication, PS specifies the parity and the bits of stop, e.g. 38400E1 for 38400 baud with even parity and 1 stop.

    According to Modbus RTU specifications :

    • the possible combinations for PS are E1, O1 and N2.
    • the number of bits of data must be 8, also there is no possibility to change this setting

An exception std::invalid_argument is thrown if one of the parameters is incorrect.

Returns
true if successful.
Examples:
router/router-simple/main.cpp, and server/clock-server/main.cpp.

◆ setByteTimeout() [1/2]

bool Modbus::Device::setByteTimeout ( const double &  timeout)
inherited

Set timeout between bytes.

This function shall set the timeout interval between two consecutive bytes of the same message. The timeout is an upper bound on the amount of time elapsed before select() returns, if the time elapsed is longer than the defined timeout, an ETIMEDOUT error will be raised by the function waiting for a response.

Parameters
timeoutreference on the variable that will contain the new timeout in seconds.
Returns
true if successful.
See also
byteTimeout()

◆ setByteTimeout() [2/2]

bool Modbus::Device::setByteTimeout ( const Timeout timeout)
inherited

Set timeout between bytes.

This function shall set the timeout interval between two consecutive bytes of the same message. The timeout is an upper bound on the amount of time elapsed before select() returns, if the time elapsed is longer than the defined timeout, an ETIMEDOUT error will be raised by the function waiting for a response.

Parameters
timeoutreference on the variable that will contain the new timeout value
Returns
true if successful.
See also
byteTimeout()

◆ setConfig()

bool Modbus::Device::setConfig ( const std::string &  jsonfile,
const std::string &  key = std::string() 
)
inherited

Set configuration from a JSON file.

This function does nothing if isValid() is true and returns false.

The file describes the configuration to apply, its format is as follows:

{
"modbuspp-device": {
"mode": "tcp",
"connection": "localhost",
"settings": "1502",
"recovery-link": true,
"debug": true,
"response-timeout": 500,
"byte-timeout": 500
}
}

Only the first 3 elements are mandatory : mode, connection and settings, the others are optional. In this example "modbuspp-device" is the key to the JSON object that should be used. If the key provided is empty, the file contains only one object corresponding to the configuration.

Parameters
jsonfileJSON file path
keyname of the object key in the JSON file corresponding to the configuration to be applied
Returns
true if successful.
Examples:
router/router-json/main.cpp, server/callback-server-json/main.cpp, server/clock-server-json/main.cpp, and server/simple-server-json/main.cpp.

◆ setDebug()

bool Modbus::Device::setDebug ( bool  debug = true)
inherited

Set debug flag.

This function function shall set the debug flag by using the argument flag. By default, the boolean flag is set to false. When the flag value is set to true, many verbose messages are displayed on stdout and stderr. For example, this flag is useful to display the bytes of the Modbus messages :

[00][14][00][00][00][06][12][03][00][6B][00][03]
Waiting for a confirmation...
<00><14><00><00><00><09><12><03><06><02><2B><00><00><00><00>
Returns
true if successful. Otherwise it shall return false and set errno.
Examples:
router/router-simple/main.cpp, and server/clock-server/main.cpp.

◆ setIndicationTimeout() [1/2]

bool Modbus::Device::setIndicationTimeout ( const double &  timeout)
inherited

Set timeout for indication.

This function shall set the timeout interval used by a server to wait for a request from a client. If timeout is zero, this timeout will not be used at all. In this case, the server will wait forever.

Parameters
timeoutreference on the variable that will contain the new timeout in seconds.
Returns
true if successful.
See also
indicationTimeout()

◆ setIndicationTimeout() [2/2]

bool Modbus::Device::setIndicationTimeout ( const Timeout timeout)
inherited

Set timeout for indication.

This function shall set the timeout interval used by a server to wait for a request from a client. If timeout is zero, this timeout will not be used at all. In this case, the server will wait forever.

Parameters
timeoutreference on the variable that will contain the new timeout value
Returns
true if successful.
See also
indicationTimeout()

◆ setRecoveryLink()

bool Modbus::Master::setRecoveryLink ( bool  recovery = true)
virtual

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Reimplemented from Modbus::Device.

◆ setResponseTimeout() [1/2]

bool Modbus::Device::setResponseTimeout ( const double &  timeout)
inherited

Set timeout for response.

This function shall set the timeout interval used to wait for a response. When a byte timeout is set, if elapsed time for the first byte of response is longer than the given timeout, an ETIMEDOUT error will be raised by the function waiting for a response. When byte timeout is disabled, the full confirmation response must be received before expiration of the response timeout.

Parameters
timeoutreference on the variable that will contain the new timeout in seconds.
Returns
true if successful.
See also
responseTimeout()

◆ setResponseTimeout() [2/2]

bool Modbus::Device::setResponseTimeout ( const Timeout timeout)
inherited

Set timeout for response.

This function shall set the timeout interval used to wait for a response. When a byte timeout is set, if elapsed time for the first byte of response is longer than the given timeout, an ETIMEDOUT error will be raised by the function waiting for a response. When byte timeout is disabled, the full confirmation response must be received before expiration of the response timeout.

Parameters
timeoutreference on the variable that will contain the new timeout value
Returns
true if successful.
See also
responseTimeout()

◆ settings()

std::string Modbus::Device::settings ( ) const
inherited

Returns the connection settings.

IP port or speed, parity and stop bit depending on the backend

For the Tcp backend :

  • settings is the service name/port number to connect to. To use the default Modbus port use the string "502". On many Unix systems, it’s convenient to use a port number greater than or equal to 1024 because it’s not necessary to have administrator privileges.

For the Rtu backend :

  • settings specifies communication settings as a string in the format BBBBPS. BBBB specifies the baud rate of the communication, PS specifies the parity and the bits of stop, e.g. 38400E1 for 38400 baud with even parity and 1 stop.

    According to Modbus RTU specifications :

    • the possible combinations for PS are E1, O1 and N2.
    • the number of bits of data must be 8, also there is no possibility to change this setting
Examples:
master/read-coils/main.cpp, master/read-holding-data/main.cpp, master/read-input-registers/main.cpp, master/report-slave-id/main.cpp, master/rw-holding-json/main.cpp, master/write-holding-data/main.cpp, router/router-json/main.cpp, router/router-simple/main.cpp, server/callback-server-json/main.cpp, server/clock-server-json/main.cpp, server/clock-server/main.cpp, and server/simple-server-json/main.cpp.

◆ slave() [1/2]

Slave& Modbus::Master::slave ( int  slaveAddr = -1)

Returns the slave whose address is provided.

The slave must have been added with addSlave() else a std::out_of_range exception is thrown.

If the Device that drives the slave to an RTU backend, we can access to the general call through the slave at address 0 (added by the constructor).

If the Device that drives the slave to a TCP backend, we can access to TCP messages through the slave at address 255 (added by the constructor).

Examples:
master/rw-holding-json/main.cpp.

◆ slave() [2/2]

const Slave& Modbus::Master::slave ( int  slaveAddr = -1) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ slavePtr() [1/2]

Slave* Modbus::Master::slavePtr ( int  slaveAddr = -1)

Returns a pointer to the slave whose address is provided.

The slave must have been added with addSlave() else a a nullptr is returned.

If the Device that drives the slave to an RTU backend, we can access to the general call through the slave at address 0 (added by the constructor).

If the Device that drives the slave to a TCP backend, we can access to TCP messages through the slave at address 255 (added by the constructor).

◆ slavePtr() [2/2]

const Slave* Modbus::Master::slavePtr ( int  slaveAddr = -1) const

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

◆ tcp()

TcpLayer& Modbus::Device::tcp ( )
inherited

underlying TCP layer (backend)

This function shall return the TCP layer if it is the layer used by the device. If it does not, a std::domain_error exception is thrown.