Java Modbus Class Members
public class Modbus
Modbus class implements a subset of modbus protocol functions.
One important comment about these functions is that all functions use a zero based index for address. For instance, if you want to set the register 40001 (4x) using PresetSingleRegister function you set the parameter nRegister equal to 0.
Connection Methods:
openConnection - open a connection with a slave device.
CloseConnection - close a connection with a slave device.
Connection Properties:
Host - Host name
Port - IP Port
ReconnectOnEveryMessage - when this property is true each call to a modbus function call openConnection before sending a query and close the connection after response was received.
Modbus Methods :
ReadOutputRegisters Reads the holding registers (4x references).
ReadInputRegisters Reads the input registers (3X references).
ReadOutputStatus Reads the discrete outputs (0x references, coils).
ReadInputStatus Reads the discrete inputs (1x references, coils).
PresetSingleRegister Presets a single holding register (4x reference)
ForceSingleCoil Forces a single coil (0x reference) to either True or False (On/Off).
PresetMultipleRegisters Presets multiple holding registers (4x reference)
ForceMultipleCoils Forces multiple coils(0x reference) to either True or False (On/Off).
ErrorMessage Return string description of an error code.
TxRxMessage pure virtual function that must be implemented in derived classes and actually send message to the network.
Properties:
Retries number of times the message is sent to a slave before the function return an error code.
ThrowException When this property is TRUE, the CModbus class functions throw ModbusException instead of returning an error code.
public boolean openConnection(String host, int port, int iTimeOut)
Return Value
true if the open was successful; otherwise false.
Parameters
host - Host name, IP (127.0.0.1) or name (pep1.modicon.com) format.
port - IP port. Open Modbus protocol use port 502, but you can use another port if you wish.
iTimeOut - Time out in ms used for sending modbus messages to a slave.
Remarks
This function try to connect with a slave using TCP/IP network. When ReconnectOnEveryMessage is true this function is called before sending a query to the slave, otherwise the connection remains opened until is explicit closed by closeconnection or by class destructor. Instead of using function parameters you can use class properties for seting sHost , nPort and dwTimeOut.
example:
String sServer;
Modbus objModbus = new Modbus();
//Make a connection
sServer = "127.0.0.1";
System.out.println("connecting with Server:"+ sServer );
if (!objModbus.openConnection(sServer,502,5000)){
System.out.println("openConnection Failed");
}
public void closeConnection()
Return Value
None.
Remarks:
Closes an the connection associated with this object. If ReconnectOnEveryMessage is true this function is called after the response from a slave was received.
public void Port(int iPort)
void Port(WORD wPort);
Remarks:
Get/Set IP port. Open modbus protocol use port 502 as a default.
public String Host()
public void Host(String sHost)
Remarks:
Get/Set Host name. Can be numeric IP format like 198.345.125.30 or a name like pep1.modicon.com.
Modbus.ReconnectOnEveryMessage
public void ReConnectOnEveryMessage(boolean bReConnectOnEveryMessage)
public boolean ReConnectOnEveryMessage()
Remarks:
When this property is true each call to a modbus function call openConnection before sending a query and close the connection after response was received. Making this property as true can save some resources from the server or slave because there is limit of connections that a server can manage simultaneously, but the communication will be slower because opening a connection can take good amount of time.
See also: openConnection,CloseConnection.
public short ReadOutputRegisters(short nAddr, int nDataStart , short nQtd , short anRegValues[])
public short ReadOutputRegisters(short nAddr, int nDataStart , short nQtd , int aiRegValues[])
public short ReadOutputRegisters(short nAddr, int nDataStart , short nQtd , float afRegValues[], int nRealType )
public short ReadOutputRegisters(short nAddr, int nDataStart , short nQtd , double adRegValues[], int nRealType )
Return Value
An error code if the function failed or ERR_OK if succeed. Use ErrorMessage to return a error description.
Parameters
nAddr - Slave Address
nDataStart - Starting Address
nQtd - number of registers to read . When reading 1 float number you are actually reading 2 registers and 1 double means 4 registers.
aiRegValues - array with registers read.
nRealType - inverse the order of registers when reading real number Modbus.REAL_NORMAL (not reversed) Modbus.REAL_REVERSE (reverse order)
Remarks
This function reads the holding registers (4x references), the first register 40001 is 0, second 40002 is 1 and so on. The array aiRegValues[] returns the registers on (unsigned 16 bit integer) format. The second form is intended for devices that use signed integers. The last two forms of this function are used for interpret modbus registers as IEEE floating point numbers. Single precision number (float) has 4 bytes , then we need 2 consecutive registers to form a float number. Another thing we have consider is that not all slaves split the float number in the same manner then you can use wRealType parameter as REAL_REVERSE to change the order the 2 consecutive registers to see if the float number is interpreted correctly. The same explanation is valid for double precision numbers , but now we need 4 registers instead of 2 to form a number.
example:
//Reads 40108 ...40110 registers from slave 17
int aiRegValues[];
short nQnt;
short nErr;
nQnt = (short)3;
aiRegValues = new int[nQnt];
nErr = objModbus.ReadOutputRegisters((short)17,(int)17
,nQnt,(short),aiRegValues);
if (nErr!=Modbus.ERR_OK) {
System.out.println("Error Reading Output
Registers");
}
for (i=0;i<nQnt;i++) {
System.out.println("["+(i+17)+"]="+aiRegValues[i]);
}
See also: ModbusException , Error Codes .
public short ReadInputRegisters(short nAddr, int nDataStart , short nQtd , short anRegValues[])
public short ReadInputRegisters(short nAddr, int nDataStart , short nQtd , int aiRegValues[])
public short ReadInputRegisters(short nAddr, int nDataStart , short nQtd , float afRegValues[], int nRealType )
public short ReadInputRegisters(short nAddr, int nDataStart , short nQtd , double adRegValues[], int nRealType )
Return Value
A error code if the function failed or Modbus.ERR_OK if succeed. Use ErrorMessage to return a error description.
Parameters
nAddr - Slave Address
nDataStart - Starting Address
nQtd - number of registers to read.When reading 1 float number you are actually reading 2 registers and 1 double means 4 registers.
anRegValues - array with registers read.
wRealType - inverse the order of registers when reading real number REAL_NORMAL (not reversed) REAL_REVERSE (reverse order).
Remarks
This function reads the input registers (3x references), the first register 30001 is 0, second 30002 is 1 and so on.The array aiRegValues[] return the registers as 16 bit unsigned integer numbers. The array anRegValues[] is intended for devices that use signed integers. The last two forms of this function are used to interpret modbus registers as IEEE floating point numbers. Single precision number (float) has 4 bytes , then we need 2 consecutive registers to form a float number. Another thing we have consider is that not all slaves split the float number in the same manner then you can use wRealType parameter as Modbus.REAL_REVERSE to change the order the 2 consecutive registers to see if the float number is interpreted correctly. The same explanation is valid for double precision numbers , but now we need 4 registers instead of 2 to form a number.
example:
///Reads 30009 register from slave 17
int aiRegValues[];
short nQnt;
short nErr;
nQnt = (short)1;
aiRegValues = new int[nQnt];
nErr = objModbus.ReadInputRegisters((short)17,(int)8
,nQnt,(short),aiRegValues);
if (nErr!=Modbus.ERR_OK) {
System.out.println("Error Reading Output
Registers");
}
for (i=0;i<nQnt;i++) {
System.out.println("["+(i+17)+"]="+aiRegValues[i]);
}
See also: ModbusException , Error Codes .
public short ReadOutputStatus(short nAddr, int nDataStart , short nQtd , boolean abCoilValues[])
Return Value
A error code if the function failed or Modbus.ERR_OK if succeed. Use ErrorMessage to return a error description.
Parameters
nAddr - Slave Address
nDataStart - Starting Address
nQtd - number of registers to read
abCoilValues - array with coils read.
Remarks
Reads the status of discrete outputs (0x references, coils) in the slave, the first coil 00001 is 0, second 00002 is 1 and so on. The array abCoilValues return the coil on boolean format (true - On , false - Off).
example:
//Reads coils 00020 ... 0056 from slave 17
//abCoils(0) is 00020 , abCoils(0) is 00021 ...
short nQnt;
short nErr;
nQnt = (short)37;
boolean[] abCoils;
abCoils = new boolean[nQnt];
nErr = objModbus.ReadOutputStatus((short)17,19 ,nQnt, abCoils);
if (nErr!=Modbus.ERR_OK) {
System.out.println("Error Reading Output
status");
}
for (i=0;i<nQnt;i++) {
System.out.println("["+(i+nDataStart)+"]="+abCoils[i]);
}
See also: ModbusException , Error Codes .
WORD ReadOutputStatus( WORD nAddr, WORD nDataStart ,WORD nQtd ,CByteArray& anRegValues);
Return Value
A error code if the function failed or Modbus.ERR_OK if succeed. Use ErrorMessage to return a error description.
Parameters
nAddr - Slave Address
nDataStart - Starting Address
nQtd - number of registers to read
anRegValues - array with registers read.
Remarks
Reads the status of discrete inputs (1x references) in the slave, the first input 10001 is 0, second 10002 is 1 and so on. CByteArray return the input on BOOL format (TRUE - On , FALSE - Off).
example:
//Reads inputs 10197 ... 10218 from slave 17
//abCoils(0) is 10197 , abCoils(0) is 10198 ...
short nQnt;
short nErr;
nQnt = (short)22;
boolean[] abCoils;
abCoils = new boolean[nQnt];
nErr = objModbus.ReadInputStatus((short)17,196 ,nQnt, abCoils);
if (nErr!=Modbus.ERR_OK) {
System.out.println("Error Reading Input
status");
}
for (i=0;i<nQnt;i++) {
System.out.println("["+(i+nDataStart)+"]="+abCoils[i]);
}
See also: ModbusException , Error Codes .
public short PresetSingleRegister(short nAddr, int nRegister , short nRegValue)
public short PresetSingleRegister(short nAddr, int nRegister , int iRegValue)
public short PresetSingleRegister(short nAddr, int nRegister ,float fRegValue,int nRealType)
public short PresetSingleRegister(short nAddr, int nRegister ,double dRegValue,int nRealType)
Return Value
A error code if the function failed or Modbus.ERR_OK if succeed. Use ErrorMessage to return an error description.
Parameters
nAddr - Slave Address
nRegister - Register Address
nRegValue - Preset Data
wRealType - inverse the order of registers when reading real number REAL_NORMAL (not reversed) REAL_REVERSE (reverse order).
Remarks
Presets a single holding register (4x reference). , the first register 40001 is 0, second 40002 is 1 and so on. When the data is a float number you are actually setting 2 registers and with a double number 4 registers are set.
example:
short nError;
nErr = objModbus.PresetSingleRegister((short)17,(int)1,(double)3); //preset register
40002 to 03 in slave device 17
See also: ModbusException , Error Codes ,PresetMultipleRegisters ,ReadOutputRegisters
public short ForceSingleCoil(short nAddr, int nRegister, boolean bCoilValue)
Return Value
An error code if the function failed or Modbus.ERR_OK if succeed. Use ErrorMessage to return an error description.
Parameters
nAddr - Slave Address
nCoil - Coil Address
bCoilValue - Force Data - true (ON) , false (OFF).
Remarks
Force a single Coil (0x reference) , the first coil 00001 is 0, second 00002 is 1 and so on.
example:
short wError;
wError = objModbus.ForceSingleCoil((short)17,172,true) ; //force
coil 173 ON in slave device 17
See also: ModbusException , Error Codes ,PresetMultipleRegisters
public short PresetMultipleRegisters(short nAddr, int nDataStart , short nQtd , short anRegValues[])
public short PresetMultipleRegisters(short nAddr, int nDataStart , short nQtd , int aiRegValues[])
public short PresetMultipleRegisters(short nAddr, int nDataStart , short nQtd , float afRegValues[],int nRealType)
public short PresetMultipleRegisters(short nAddr, int nDataStart , short nQtd , double adRegValues[],int nRealType)
Return Value
Error code if the function failed or Modbus.ERR_OK if succeed. Use ErrorMessage to return an error description.
Parameters
nAddr - Slave Address
nDataStart - Starting Address
nQtd - number of registers to set. When setting 1 float number you are actually setting 2 registers and 1 double means 4 registers.
anRegValues - Presets values Data
wRealType - inverse the order of registers when reading real number REAL_NORMAL (not reversed) REAL_REVERSE (reverse order).
Remarks
Presets values of holding registers (4x references) , the first register 40001 is 0, second 40002 is 1 and so on. When the data is a float number you are actually setting 2 registers and with a double number 4 registers are set.
example:
short nError;
int aiRegs[];
//preset two registers starting at 40002 to 000A and 0102 hex, in slave device 17.
aiRegs=new int[2]
aiRegs[0]=0x000A;
aiRegs[1]=0x0102;
nErr = objModbus.PresetMultipleRegisters((short)17,1 ,(short)2 ,aiRegs);
if (nErr!=Modbus.ERR_OK) {
System.out.println("Error setting
Registers");
}
See also: ModbusException , Error Codes ,PresetSingleRegister
public short ForceMultipleCoils(short nAddr, int nDataStart , short nQtd , boolean abCoilValues[])
Return Value
Error code if the function failed or Modbus.ERR_OK if succeed. Use ErrorMessage to return an error description.
Parameters
nAddr - Slave Address
nDataStart - Starting Address
nQtd - number of registers to read
abCoilValues - Force values Data true (ON) , false (OFF).
Remarks
Force values of coils (0x references). , the first coil 00001 is 0, second 00002 is 1 and so on.
example:
short nError;
boolean anCoils[];
//force a series of 2 coils starting at coil 00020 in slave device 17.
anCoils= new boolean[2]
anCoils(0)=true; //ON
anCoils(1)=false;//OFF
nError = objModbus.ForceMultipleCoils((short)17,19,(short)2,anCoils) ;
See also: ModbusException , Error Codes ,ForceSingleCoil
public String ErrorMessage(int iErrorNumber) {
Return Value
String message with error description.
Parameters
iErrorCode - An Error code returned by CModbus class function.
Remarks
The return string is empty if the wErrorCode is not found.
See also: ModbusException , Error Codes
public int Retries()
public void Retries(int iRetries);
Remarks
Get/Set number of times the message is sent to a slave before the function return an error code. For instance,
if Retries() = 3 , when a messages is sent to a device and occur an error, that message will be sent again more 2 times.
public boolean ThrowCommException()
public void ThrowCommException(boolean bThrow)
void ThrowException(BOOL bThrow);
Remarks
When this property is true, the Modbus class functions throw ModbusException instead of returning an error code. By Default this property is false.
example
objModbus.ThrowCommException(true);
try {
//It's not needed to verify each call for errors
objModbus.ForceSingleCoil((short)17,172,true) ; //force coil 173 ON in slave device 17
objModbus.PresetSingleRegister((short)17,1,3) ; //preset register 40002 to 03 in slave device 17
}
catch(ModbusException e) {
System.out.println(e.ErrorNumber());
}
See also: ModbusException