Skip to main content
Code Review

Return to Question

Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
added 5229 characters in body
Source Link
Jamal
  • 35.2k
  • 13
  • 134
  • 238

I want to improve my code. In this code I don't like my contructorconstructor, but without it I keep getting an error while trying to connect NullPointerException.Any suggestions are welcome.

package soft;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
import net.wimpi.modbus.ModbusException;
import net.wimpi.modbus.ModbusIOException;
import net.wimpi.modbus.ModbusSlaveException;
import net.wimpi.modbus.io.ModbusSerialTransaction;
import net.wimpi.modbus.io.ModbusTCPTransaction;
import net.wimpi.modbus.msg.ReadCoilsRequest;
import net.wimpi.modbus.msg.ReadCoilsResponse;
import net.wimpi.modbus.msg.ReadInputDiscretesRequest;
import net.wimpi.modbus.msg.ReadInputDiscretesResponse;
import net.wimpi.modbus.msg.ReadInputRegistersRequest;
import net.wimpi.modbus.msg.ReadInputRegistersResponse;
import net.wimpi.modbus.msg.ReadMultipleRegistersRequest;
import net.wimpi.modbus.msg.ReadMultipleRegistersResponse;
import net.wimpi.modbus.msg.WriteMultipleRegistersRequest;
import net.wimpi.modbus.msg.WriteMultipleRegistersResponse;
import net.wimpi.modbus.msg.WriteSingleRegisterRequest;
import net.wimpi.modbus.msg.WriteSingleRegisterResponse;
import net.wimpi.modbus.net.SerialConnection;
import net.wimpi.modbus.net.TCPMasterConnection;
import net.wimpi.modbus.procimg.Register;
import net.wimpi.modbus.procimg.SimpleRegister;
import net.wimpi.modbus.util.SerialParameters;
/**
 * This class realizes modbus protocol
 * communication over TCP and Serial Port and most of modbus functions.
 *
 * @author Tomas Ausvicas
 */
public class BackEnd {

/** The tcp con. */
TCPMasterConnection tcpCon;
/** The serial con. */
SerialConnection serialCon;
/** The transactionpublic tcp.class */
ModbusTCPTransactionBackEnd transactionTCP;{
/** The transactiontcp con. */
 TCPMasterConnection tcpCon;
  
 /** The serial con. */
ModbusSerialTransaction transactionSerial; SerialConnection serialCon;
/** The paramstransaction tcp. */
SerialParameters params = new SerialParameters();ModbusTCPTransaction transactionTCP;
 
 /** The transaction serial. */
 ModbusSerialTransaction transactionSerial;
/** The rcreqparams. */
ReadCoilsRequest rcreq SerialParameters params = new ReadCoilsRequestSerialParameters();
/** The rcreq. */
  ReadCoilsRequest rcreq = new ReadCoilsRequest();
 
 /** The rcres. */
ReadCoilsResponse rcres = new ReadCoilsResponse();
/** The rireq. */
ReadInputRegistersRequest rireq = new ReadInputRegistersRequest();
 
 /** The rires. */
 ReadInputRegistersResponse rires = new ReadInputRegistersResponse();
/** The riresridreq. */
ReadInputRegistersResponse rires ReadInputDiscretesRequest ridreq = new ReadInputRegistersResponseReadInputDiscretesRequest();
 
 /** The ridres. */
 ReadInputDiscretesResponse ridres = new ReadInputDiscretesResponse();
/** The ridreqwrite_sreq. */
ReadInputDiscretesRequest ridreq WriteSingleRegisterRequest write_sreq = new ReadInputDiscretesRequestWriteSingleRegisterRequest();
 
 /** The write_sres. */
 WriteSingleRegisterResponse write_sres = new WriteSingleRegisterResponse();
/** The ridresread_mreq. */
ReadInputDiscretesResponse ridres ReadMultipleRegistersRequest read_mreq = new ReadInputDiscretesResponseReadMultipleRegistersRequest();
 
 /** The read_mres. */
 ReadMultipleRegistersResponse read_mres = new `ReadMultipleRegistersResponse();`
/** The write_sreqwrite_mreq. */
WriteSingleRegisterRequest write_sreq WriteMultipleRegistersRequest write_mreq = new WriteSingleRegisterRequestWriteMultipleRegistersRequest();
 
 /** The write_mres. */
 WriteMultipleRegistersResponse write_mres = new WriteMultipleRegistersResponse();
/** The write_sresregister. */
WriteSingleRegisterResponse write_sres = new WriteSingleRegisterResponse();SimpleRegister regL, regH, register;
 
 /** The registers. */
 Register[] registers;
/** The read_mreqint16 result. */
ReadMultipleRegistersRequest read_mreq = new ReadMultipleRegistersRequest();private int[] int16Result;
 
 /** The int32 result. */
 private int[] int32Result;
 
 /** The float result. */
 private float[] floatResult;
 
 /** The round float result. */
 private float[] roundFloatResult;
/** The read_mresstring16 result. */
ReadMultipleRegistersResponse read_mres = new `ReadMultipleRegistersResponse();`private String[] string16Result;
 
 /** The string32 result. */
 private String[] string32Result;
 
 /** The string float result. */
 private String[] stringFloatResult;
 
 /** The round string float result. */
 private String[] roundStringFloatResult;
/** The write_mreqstring coil result. */
WriteMultipleRegistersRequest write_mreq = new WriteMultipleRegistersRequest();private String[] stringCoilResult;
 
 /** The boolean coil result. */
 private boolean[] booleanCoilResult;
/** The write_mresstring discrete input result. */
WriteMultipleRegistersResponse write_mres = new WriteMultipleRegistersResponse();private String[] stringDiscreteInputResult;
 
 /** The boolean discrete input result. */
 private boolean[] booleanDiscreteInputResult;
/** The registerstring read bit result. */
SimpleRegister regL, regH, register; private String[] stringReadBitResult;
 
 /** The boolean read bit result. */
 private boolean[] booleanReadBitResult;
/** The int analog input registers result. */
Register[] registers; private int[] intAnalogInputRegistersResult;
 
 /** The string analog input registers result. */
 private String[] stringAnalogInputRegistersResult;
/** The int16to resultstring. */
private int[]String[] int16Result;toString;
/** The int32 result * Default constructor with TCP and Serial Port objects created. */
private int[] int32Result; public BackEnd() {
/** The float result try {
 tcpCon = new TCPMasterConnection(InetAddress.getByName(""));
 */ } catch (UnknownHostException e) {
private float[] floatResult; System.out.println("Unknow Host");
 }
 params = new SerialParameters();
 serialCon = new SerialConnection(params);
 }
/** The round float result * Connect over TCP. *
 * @param ipAddress the ip address
 * @param port the port
 */
private float[] roundFloatResult; public void connectTCP(String ipAddress, int port) {
/** The string16 result try {
 tcpCon = new TCPMasterConnection(InetAddress.getByName(ipAddress));
 * } catch (UnknownHostException e1) {
 JOptionPane.showMessageDialog(null, "Įveskite IP adresą", "Invalid input", JOptionPane.WARNING_MESSAGE);
 }
 tcpCon.setPort(port);
 try {
 tcpCon.connect();
 } catch (Exception e) {
 JOptionPane.showMessageDialog(null, "Nepavyko prisijungti prie serverio. [TCP/IP]", "Connection error",
private String[] string16Result; JOptionPane.ERROR_MESSAGE);
 }
 
 transactionTCP = new ModbusTCPTransaction(tcpCon);
 
 }
/** The string32 result * Set parameters for serial com. *
 * @param portName the port name
 * @param baudRate the baud rate
 * @param dataBits the data bits
 * @param stopBits the stop bits
 * @param parity the parity
 * @param encoding the encoding
 * @param echo the echo
 */
private String[] string32Result; public void connectSerial(String portName, int baudRate, int dataBits, int stopBits, String parity, String encoding,
 boolean echo) {
/** The string float result. */
private String[] stringFloatResult; SerialParameters params = new SerialParameters();
/** The round string float result params.setPortName(portName);
 */ params.setDatabits(dataBits);
private String[] roundStringFloatResult; params.setParity(parity);
 params.setStopbits(stopBits);
 params.setEncoding(encoding);
 params.setEcho(echo);
 params.setBaudRate(baudRate);
/** The string coil result. */
private String[] stringCoilResult; serialCon = new SerialConnection(params);
/** The boolean coil result try {
 serialCon.open();
 */ } catch (Exception e) {
private boolean[] booleanCoilResult; JOptionPane.showMessageDialog(null, "Nepavyko prisijungti prie serverio. [Serial port]", "Connection error",
 JOptionPane.ERROR_MESSAGE);
 }
 transactionSerial = new ModbusSerialTransaction(serialCon);
 }
/** The string discrete input result* Close TCP connection. */
private String[] stringDiscreteInputResult; public void closeTCP() {
 tcpCon.close();
 }
/** The boolean discrete input result* Close Serial connection. */
private boolean[] booleanDiscreteInputResult; public void closeSerial() {
 serialCon.close();
 }
/** The string read bit result* Check if TCP connected. *
 * @return boolean value
 */
private String[] stringReadBitResult; public boolean isConnectedTCP() {
 return tcpCon.isConnected();
 
 }
/** The boolean read bit result* Check if Serial connected. *
 * @return boolean value
 */
private boolean[] booleanReadBitResult; public boolean isOpenSerial() {
 return serialCon.isOpen();
 }
/** The int analog input registers* resultWrites single 16bit number to register (16 bit integer).
 *
  * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWrite the data to write
 */
private int[] intAnalogInputRegistersResult; public void WriteSingle_16Bit(int unitID, int startAddress, int dataToWrite) {
/** The string analog input registers result. */
private String[]SimpleRegister stringAnalogInputRegistersResult;reg = new SimpleRegister(dataToWrite);
/** The to string write_sreq.setReference(startAddress);
 */ write_sreq.setUnitID(unitID);
private String[] toString; write_sreq.setRegister(reg);
/** try {
 * Default constructor with TCP and Serial Port objects created transaction(transactionTCP, transactionSerial, write_sreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception write 16");
 */ } catch (ModbusSlaveException e) {
public BackEnd System.out.println("Modbus Slave Exception write 16");
  } catch (ModbusException e) {
 System.out.println("Modbus Exception write 16");
 }
 }
try { /**
 tcpCon =* newWrites TCPMasterConnection(InetAddress.getByNamedouble 16bit number to register ("")32 bit integer);.
} catch (UnknownHostException e) { *
 System.out.println("Unknow Host");* @param unitID the unit id
} * @param startAddress the start address
params = new SerialParameters(); * @param dataToWrite the data to write
serialCon = new SerialConnection */
 public void WriteSingle_32Bit(paramsint unitID, int startAddress, int dataToWrite);
} {
/**
 * Connect over TCP.
 *
 * @param ipAddress the ip address
 * @param port the port
 */
public void connectTCP(String ipAddress, int port)count {= 2;
 try {
  int tcpConHIGH = new TCPMasterConnection(InetAddress.getByName(ipAddress));
 } catch (UnknownHostException e1) {
 JOptionPane.showMessageDialog(null, "Įveskite IP adresą", "Invalid input", JOptionPane.WARNING_MESSAGE);
 }
 tcpCon.setPort(port);
 try {
  tcpCon.connect();
 } catch (Exception e) {
 JOptionPane.showMessageDialog(null, "Nepavyko prisijungti prie serverio. [TCP/IP]", "Connection error",
 dataToWrite >> JOptionPane.ERROR_MESSAGE);16;
 }
  int transactionTCPLOW = new ModbusTCPTransaction(tcpCon);
 dataToWrite & 
}0xFFFF;
/**
 * Set parameters for serial com.
 *
 * @param portName the port name
 * @param baudRate the baud rate
 * @param dataBits the data bits
 * @param stopBits the stop bits
 * @paramregH parity= thenew paritySimpleRegister(HIGH);
 * @param encoding the encoding
 * @param echo the echo
regL */
public= voidnew connectSerialSimpleRegister(String portName, int baudRate, int dataBits, int stopBits, String parity, String encoding,
 boolean echoLOW) {;
 SerialParameters params registers = new SerialParameters();Register[count];
 params.setPortName(portName);
 params.setDatabitsfor (dataBits);
int i = 0, params.setParity(parity);
a = 1; i params< registers.setStopbits(stopBitslength; i += 2, a += 2); {
 params.setEncoding(encoding); registers[i] = regL;
 params.setEcho(echo); registers[a] = regH;
 params.setBaudRate(baudRate); }
 serialCon = new SerialConnection write_mreq.setReference(paramsstartAddress);
 write_mreq.setUnitID(unitID);
 write_mreq.setRegisters(registers);
 try {
 serialCon.open transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ExceptionModbusIOException e) {
 JOptionPane System.showMessageDialogout.println(null,"Modbus "NepavykoIO prisijungtiException priewrite serverio32");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus [SerialSlave port]",Exception "Connectionwrite error",32");
 } catch (ModbusException e) {
 JOptionPane System.ERROR_MESSAGEout.println("Modbus Exception write 32");
 }
 }
 transactionSerial = new ModbusSerialTransaction(serialCon);
}

/**
 * CloseWrites TCPdouble connection16bit number to register (32bit float).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWriteF the data to write f
 */
public void closeTCPWriteSingle_Float()int {
unitID, int startAddress, float tcpCon.close(dataToWriteF);
} {
/**
 * Close Serial connection.
 */
public void closeSerial() {
 int count = serialCon.close();
}2;
/**
 * Check if TCP connected int number = Float.floatToIntBits(dataToWriteF);
 *
 * @return boolean value
 */
public boolean isConnectedTCP()int {HIGH = number >> 16;
 return tcpCon.isConnected();
 int 
}LOW = number & 0xFFFF;
/**
 * Check if Serial connected.
 *
 * @returnregH boolean= value
new */SimpleRegister(HIGH);
public boolean isOpenSerial() {
 return serialCon.isOpenregL = new SimpleRegister(LOW);
}
/**
 * Writes single 16bit number to register (16 bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWrite the data to write
 */
public void WriteSingle_16Bit(int unitID, int startAddress,registers int= dataToWrite)new {Register[count];
 SimpleRegister reg = new SimpleRegisterfor (dataToWriteint i = 1, a = 0; i < registers.length; i += 2, a += 2); {
 registers[i] = regL;
 registers[a] = regH;
 }
 write_sreq write_mreq.setReference(startAddress);
 write_sreq write_mreq.setUnitID(unitID);
 write_sreq write_mreq.setRegistersetRegisters(regregisters);
 try {
 transaction(transactionTCP, transactionSerial, write_sreqwrite_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception write 16"float");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception write 16"float");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception write 16"float");
 }
 }
}
/**
 * Writes double 16bit number to register (32 bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWrite the data to write
 */
public void WriteSingle_32Bit(int unitID, int startAddress, int dataToWrite) {

 int/**
 * Writes multiple 16bit numbers to chosen registers (16bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWrite the data to write
 * @param count =the 2;count
 */
 public void WriteMultiple_16Bit(int unitID, int startAddress, int dataToWrite, int count) {
 int HIGH register = new SimpleRegister(dataToWrite);
 >> 16;
 int LOW =registers dataToWrite= &new 0xFFFF;Register[count];
 regH = new SimpleRegister for (HIGHint i = 0; i < registers.length; i++); {
 regL registers[i] = newregister;
 SimpleRegister(LOW); }
 registers = new Register[count]; write_mreq.setReference(startAddress);
 write_mreq.setUnitID(unitID);
 write_mreq.setRegisters(registers);
 for (int i = 0try {
 transaction(transactionTCP, atransactionSerial, =write_mreq);
 1; i < registers } catch (ModbusIOException e) {
 System.length;out.println("Modbus iIO +=Exception 2,mwrite a16");
 += 2 } catch (ModbusSlaveException e) {
 registers[i] = regL; System.out.println("Modbus Slave Exception mwrite 16");
 registers[a]} =catch regH;(ModbusException e) {
 System.out.println("Modbus Exception mwrite 16");
 }
 }
 write_mreq.setReference(startAddress);/**
 write_mreq.setUnitID(unitID);
  write_mreq.setRegisters(registers);
 try* {
Writes multiple double 16bit numbers to chosen registers transaction(transactionTCP, transactionSerial,32bit write_mreqinteger);.
 } catch (ModbusIOException e) {*
 * @param unitID System.out.println("Modbusthe IOunit Exceptionid
 write 32");
 * }@param catchstartAddress (ModbusSlaveExceptionthe e)start {address
 * @param dataToWrite System.out.println("Modbusthe Slavedata Exceptionto write 32");
 } catch* (ModbusException@param e)count {the count
 */
 System.out.println public void WriteMultiple_32Bit("Modbusint ExceptionunitID, writeint 32");
startAddress, int dataToWrite, int }
}count) {
/**
 * Writes double 16bit number to register (32bit float).
 *
 * @param unitID the unit id
 *int @paramHIGH startAddress= thedataToWrite start>> address16;
 * @param dataToWriteF the data to write f
 */
public void WriteSingle_Float(int unitID, intLOW startAddress,= floatdataToWrite dataToWriteF)& {0xFFFF;
 int count regH = 2;new SimpleRegister(HIGH);
 regL = new SimpleRegister(LOW);
 int number = Float.floatToIntBits(dataToWriteF);
  int HIGHregisters = number >> 16;
 int LOW =new numberRegister[count &* 0xFFFF;2];
 regH = new SimpleRegister for (HIGHint i = 0, a = 1; i < registers.length; i += 2, a += 2); {
 regL registers[i] = newregL;
 SimpleRegister(LOW); registers[a] = regH;
 }
 registers = new Register[count]; write_mreq.setReference(startAddress);
 write_mreq.setUnitID(unitID);
 write_mreq.setRegisters(registers);
 for (int i = 1try {
 transaction(transactionTCP, atransactionSerial, =write_mreq);
 0; i < registers } catch (ModbusIOException e) {
 System.length;out.println("Modbus iIO +=Exception 2,mwrite a32");
 += 2 } catch (ModbusSlaveException e) {
 registers[i] = regL; System.out.println("Modbus Slave Exception mwrite 32");
 registers[a]} =catch regH;(ModbusException e) {
 System.out.println("Modbus Exception mwrite 32");
 }
 }
 write_mreq.setReference/**
 * Writes multiple double 16bit numbers to chosen registers (startAddress32bit float);.
 write_mreq.setUnitID( *
 * @param unitID); the unit id
 write_mreq.setRegisters * @param startAddress the start address
 * @param dataToWriteF the data to write f
 * @param count the count
 */
 public void WriteMultiple_Float(registersint unitID, int startAddress, float dataToWriteF, int count); {
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
  } catch (ModbusIOException e) {
 int number = System.outFloat.printlnfloatToIntBits("Modbus IO Exception write float"dataToWriteF);
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception write float");
 int }HIGH catch= (ModbusExceptionnumber e)>> {16;
 System.out.println("Modbus Exception writeint float");
LOW = number & }
}0xFFFF;
/**
 * Writes multiple 16bit numbers to chosen registers (16bit integer).
 *
 * @param unitID the unit id
 * @param startAddressregH the= startnew addressSimpleRegister(HIGH);
 * @param dataToWrite the data to write
 * @param count the count
regL */
public= voidnew WriteMultiple_16BitSimpleRegister(int unitID, int startAddress, int dataToWrite, int countLOW) {;
 register = new SimpleRegister(dataToWrite);
 registers = new Register[count];Register[count * 2];
 for (int i = 1, a = 0; i < registers.length; i++i += 2, a += 2) {
 registers[i] = register;regL;
 registers[a] = regH;
 }
 write_mreq.setReference(startAddress);
 write_mreq.setUnitID(unitID);
 write_mreq.setRegisters(registers);
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mwrite 16"float");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mwrite 16"float");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mwrite 16"float");
 }
 }
}

/**
 * WritesReads multiple double 16bit numbers tofrom chosen registers (32bit16bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWritecount the datacount
 to write
 * @param count* the@return countmultiple registers
 */
public voidBackEnd WriteMultiple_32BitReadMultiple_16Bit(int unitID, int startAddress, int dataToWrite, int count) {
 int HIGH = dataToWrite >>this.int16Result 16;= new int[count];
 int LOW = dataToWrite &this.string16Result 0xFFFF;= new String[count];
 regH = new SimpleRegister read_mreq.setUnitID(HIGHunitID);
 regL = new SimpleRegister read_mreq.setReference(LOWstartAddress);
 read_mreq.setWordCount(count);
 registers = new Register[count *try 2];{
 transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mread 16");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mread 16");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mread 16");
 }
 for (int i = 0,for a(int n = 1;0; in < registersread_mres.length; igetWordCount(); +=n++) 2,{
 a += 2) {
 registers[i]int16Result[n] = regL;read_mres.getRegisterValue(n);
 registers[a] = regH;
 string16Result[n] = }String.valueOf(int16Result[n]);
 write_mreq.setReference(startAddress);
 write_mreq.setUnitID(unitID);
 write_mreq.setRegisters(registers);}
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mwrite 32");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mwrite 32");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mwritereturn 32");this;
 }
}

/**
 * WritesReads multiple double 16bit numbers tofrom chosen registers (32bit floatinteger).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWriteFcount the datacount
 to write f
 * @param* count@return themultiple countregisters
 */
public voidBackEnd WriteMultiple_FloatReadMultiple_32Bit(int unitID, int startAddress, float dataToWriteF, int count) {
 int number = Float.floatToIntBits(dataToWriteF);
  this.int32Result int= HIGHnew =int[count];
 number >> 16;
 int LOWthis.string32Result = number &new 0xFFFF;String[count];
 regH int[] z = new SimpleRegister(HIGH);int[count * 2];
 regL int[] y = new SimpleRegister(LOW);int[count * 2];
 registers int[] h = new Register[countint[count];
 * 2]; int[] l = new int[count];
 for (int i = 1, a = 0; i < registersread_mreq.length; i += 2, a += 2setUnitID(unitID) {;
 registers[i] = regL;read_mreq.setReference(startAddress);
 registers[a] = regH;
 read_mreq.setWordCount(count * }2);
 write_mreq try {
 transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.setReferenceout.println(startAddress"Modbus IO Exception mread 32");
 write_mreq } catch (ModbusSlaveException e) {
 System.setUnitIDout.println(unitID"Modbus Slave Exception mread 32");
 write_mreq } catch (ModbusException e) {
 System.setRegistersout.println(registers"Modbus Exception mread 32");
 }
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
  } catchfor (ModbusIOException e)int {
n = 0, i = 1; n < System.outread_mres.printlngetWordCount("Modbus IO Exception mwrite float"); n += }2, catchi (ModbusSlaveException+= e2) {
 System.out.println("Modbus Slave Exception mwrite float"z[n] = read_mres.getRegisterValue(n);
 } catch (ModbusException e) {
  y[i] = System.out(read_mres.printlngetRegisterValue("Modbus Exceptioni) mwrite<< float"16);
 }
}
/**
 * Reads multiple 16bit numbers from chosen registersfor (16bitint integer).
a *
= *0, @paramb unitID= the0; unita id
< *l.length; @parama++, startAddressb the+= start2) address{
 * @param count the count
 * @return multiple registers
 */ l[a] = z[b];
public BackEnd ReadMultiple_16Bit(int unitID, int startAddress, int count) {}
 this.int16Result for (int a = new0, int[count];
b = 1; a < thish.string16Resultlength; a++, b += 2) {
 h[a] = newy[b];
 String[count]; }
 read_mreq.setUnitID for (unitID);
int n = 0; n read_mreq< int32Result.setReference(startAddresslength; n++); {
 read_mreq int32Result[n] = h[n] | l[n];
 string32Result[n] = String.setWordCountvalueOf(countint32Result[n]);
 }
 try {
 transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mread 16");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mread 16");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mreadreturn 16");this;
 }
 for/**
 (int n = 0; n* <Reads read_mres.getWordCountmultiple double 16bit numbers from chosen registers ();32 n++bit float).
 { *
 * @param unitID int16Result[n]the =unit read_mres.getRegisterValue(n);id
 * @param startAddress string16Result[n]the =start String.valueOf(int16Result[n]);address
 * @param count the count
 } * @return multiple registers
 */
 public BackEnd ReadMultiple_Float(int unitID, int startAddress, int count) {
 return this; this.floatResult = new float[count];
} this.stringFloatResult = new String[count];
 this.roundFloatResult = new float[count];
 this.roundStringFloatResult = new String[count];
/**
 * Reads multiple double 16bit numbers from chosenint[] registersx (32bit= integer).
new *
int[count * @param unitID the unit id2];
 * @param startAddress the start address
 * @param count the count
int[] *y @return= multiplenew registers
int[count */
public BackEnd ReadMultiple_32Bit(int unitID, int startAddress, int count) {2];
 this.int32Result int[] h = new int[count];
 this.string32Result int[] l = new String[count];int[count];
 int[] z = new int[countread_mreq.setUnitID(unitID);
 * 2]; read_mreq.setReference(startAddress);
 int[] y = new int[countread_mreq.setWordCount(count * 2];2);
 int[] h = new int[count];try {
 int[] l = new int[count]; transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mread float");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mread float");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mread float");
 }
 read_mreq for (int n = 1, i = 0; n < read_mres.setUnitIDgetWordCount(unitID); n += 2, i += 2) {
 read_mreq x[n] = read_mres.setReferencegetRegisterValue(startAddressn);
 read_mreq y[i] = (read_mres.setWordCountgetRegisterValue(counti) *<< 216);
 }
 try {
 transaction(transactionTCP, transactionSerial, read_mreq);
  } catchfor (ModbusIOException e)int {
a = 0, b = 1; a < System.outl.println("Modbus IO Exception mread 32");
 length; }a++, catchb (ModbusSlaveException+= e2) {
 System.out.println("Modbus Slave Exception mread 32");
 } catch (ModbusExceptionl[a] e)= {x[b];
 System.out.println("Modbus Exception mread 32");
 }
 for (int na = 0, ib = 1;0; na < read_mresh.getWordCount(); n +=length; 2a++, ib += 2) {
 z[n] = read_mres.getRegisterValue(n);
  h[a] = y[i]y[b];
 = (read_mres.getRegisterValue(i) << 16);
 }
 for (int an = 0,0; bn < floatResult.length; n++) {
  floatResult[n] = 0;Float.intBitsToFloat(h[n] a| <l[n]);
 l stringFloatResult[n] = String.length;valueOf(floatResult[n]);
 a++, b += 2 roundFloatResult[n] = (float) {Math.round(floatResult[n] * 100) / 100;
 l[a] roundStringFloatResult[n] = z[b];Float.toString(roundFloatResult[n]);
 }
 for (int a = 0, b = 1; a < h.length; a++, b += 2) {
  h[a] =return y[b];this;
 }
 for/**
 (int n = 0; n* <Reads int32Resultmultiple coils from chosen registers.length; n++) { *
 * @param unitID int32Result[n]the =unit h[n]id
 | l[n]; * @param startAddress the start address
 * @param count string32Result[n]the =count
 * @return coil as boolean or String.valueOf(int32Result[n]);
 } */
 public BackEnd ReadCoilStatus(int unitID, int startAddress, int count) {
 return this; this.booleanCoilResult = new boolean[count];
} this.stringCoilResult = new String[count];
/**
 * Reads multiple double 16bit numbers from chosen registers rcreq.setReference(32 bit floatstartAddress).;
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param count the rcreq.setBitCount(count);
 * @return multiple registers
 */
public BackEnd ReadMultiple_Float(int rcreq.setUnitID(unitID, int startAddress, int count) {;
 this.floatResult = new float[count]; try {
 this transaction(transactionTCP, transactionSerial, rcreq);
 } catch (ModbusIOException e) {
 e.stringFloatResultprintStackTrace();
 = new String[count]; } catch (ModbusSlaveException e) {
 this e.roundFloatResultprintStackTrace();
 = new float[count]; } catch (ModbusException e) {
 this e.roundStringFloatResultprintStackTrace();
 = new String[count]; }
 int[] x for (int i = new0; int[counti *< 2];count; i++) {
 int[] y booleanCoilResult[i] = newrcres.getCoilStatus(i);
 int[count * 2]; stringCoilResult[i] = String.valueOf(booleanCoilResult[i]);
 }
 int[] h = new int[count];
 return int[]this;
 l = new int[count];}
 read_mreq/**
 * Reads multiple discrete inputs from chosen registers.setUnitID(
 *
 * @param unitID); the unit id
 read_mreq.setReference( * @param startAddress); the start address
 read_mreq.setWordCount( * @param count the count
  * 2@return discrete input as boolean or String
 */
 public BackEnd ReadDiscreteInputStatus(int unitID, int startAddress, int count); {
 try {
 transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mread float");
 } catch (ModbusSlaveException e) {
  System.outthis.println("Modbus Slave Exception mread float");
 } catchbooleanDiscreteInputResult (ModbusException= e)new {boolean[count];
 System.outthis.println("Modbus Exception mread float");
 stringDiscreteInputResult = new }String[count];
 for (int n = 1, i = 0; n < read_mresridreq.getWordCountsetReference(startAddress); n += 2, i += 2) {
 x[n] = read_mresridreq.getRegisterValuesetBitCount(ncount);
 y[i] = (read_mresridreq.getRegisterValuesetUnitID(i) << 16unitID);
 }
 for (int a = 0try {
 transaction(transactionTCP, btransactionSerial, =ridreq);
 1; a < l } catch (ModbusIOException e) {
 e.length;printStackTrace();
 a++, b += 2 } catch (ModbusSlaveException e) {
 l[a] = x[b]; e.printStackTrace();
 } catch (ModbusException e) {
 e.printStackTrace();
  }
 for (int ai = 0,0; bi =< 0;count; ai++) <{
 h.length; a++, b += 2) { booleanDiscreteInputResult[i] = ridres.getDiscreteStatus(i);
 h[a] stringDiscreteInputResult[i] = y[b];String.valueOf(booleanDiscreteInputResult[i]);
 }
 for (int n = 0; n < floatResult.length; n++) {
  floatResult[n] = Float.intBitsToFloat(h[n] | l[n]);
 stringFloatResult[n] = String.valueOf(floatResult[n]);
 roundFloatResult[n] = (float) Math.round(floatResult[n] * 100) / 100;
 roundStringFloatResult[n] =return Float.toString(roundFloatResult[n]);this;
 }
 return/**
 this; * Reads multiple analog inputs from chosen registers.
} *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param count the count
 * @return analog input register value (int or String)
 */
 public BackEnd ReadAnalogInputRegisters(int unitID, int startAddress, int count) {
/**
 * Reads multiple coils from chosen registers.
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @paramthis.intAnalogInputRegistersResult count= thenew countint[count];
 * @return coil as boolean or String
 */
public BackEnd ReadCoilStatus(int unitID, int startAddress,this.stringAnalogInputRegistersResult int= count)new {String[count];
 this.booleanCoilResult = new boolean[count]; rireq.setReference(startAddress);
 this rireq.stringCoilResultsetWordCount(count);
 = new String[count]; rireq.setUnitID(unitID);
 rcreq try {
 transaction(transactionTCP, transactionSerial, rireq);
 } catch (ModbusIOException e) {
 e.setReferenceprintStackTrace(startAddress);
 rcreq } catch (ModbusSlaveException e) {
 e.setBitCountprintStackTrace(count);
 rcreq } catch (ModbusException e) {
 e.setUnitIDprintStackTrace(unitID);
 }
 try {
  for transaction(transactionTCP, transactionSerial, rcreq);
int i = 0; }i catch< (ModbusIOExceptioncount; ei++) {
 e.printStackTrace();
  } catch (ModbusSlaveException e) {
 intAnalogInputRegistersResult[i] = erires.printStackTracegetRegisterValue(i);
 } catch (ModbusException e) {
  stringAnalogInputRegistersResult[i] = eString.printStackTracevalueOf(intAnalogInputRegistersResult[i]);
 }
 for (int i = 0; i < count; i++) {
  booleanCoilResult[i] = rcres.getCoilStatus(i);
  stringCoilResult[i] =return String.valueOf(booleanCoilResult[i]);this;
 }
 return this;
}
/**
 * Reads multiple discrete inputs* Read bit from chosena registersregister.
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param position  D15..D0
 * @param count the count
 * @return discrete inputbit as boolean or String
 */
public BackEnd ReadDiscreteInputStatusReadBit(int unitID, int startAddress, int position, int count) {
 this.booleanDiscreteInputResultstringReadBitResult = new String[count];
  this.booleanReadBitResult = new boolean[count];
 this.stringDiscreteInputResulttoString = new String[count];
 ridreq.setReference(startAddress);
 ridreq.setBitCount(count);
// String[] toString = ridreq.setUnitID(unitID);new String[count];
 try {
  transaction(transactionTCP, transactionSerial, ridreq);
 } catch (ModbusIOException e) {
 eread_mreq.printStackTracesetUnitID(unitID);
 } catch (ModbusSlaveException e) {
  eread_mreq.printStackTracesetReference(startAddress);
 } catch (ModbusException e) {
 eread_mreq.printStackTracesetWordCount(count);
 }
 for try {
  transaction(inttransactionTCP, itransactionSerial, =read_mreq);
 0; i < count; i++ } catch (ModbusIOException e) {
 booleanDiscreteInputResult[i] = ridres System.getDiscreteStatusout.println(i"Modbus IO Exception read bit");
 stringDiscreteInputResult[i]} =catch String(ModbusSlaveException e) {
 System.valueOfout.println(booleanDiscreteInputResult[i]"Modbus Slave Exception read bit");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception read bit");
 }
 return this;
} for (int n = 0; n < read_mres.getWordCount(); n++) {
/**
 * Reads multiple analog inputs from chosen registers.
 *
 * @param unitID the unittry id{
 * @param startAddress the start address
 * @param count the count
 * @return analog input registertoString[n] value= Integer.toBinaryString(int0x10000 or| Stringread_mres.getRegisterValue(n)
 */
public BackEnd ReadAnalogInputRegisters).substring(int unitID, int startAddress, int count1) {;
 this if (toString[n].intAnalogInputRegistersResultcharAt(15 - position) == '0') {
 booleanReadBitResult[n] = newfalse;
 int[count]; stringReadBitResult[n] = String.valueOf(false);
 this } else if (toString[n].stringAnalogInputRegistersResultcharAt(15 - position) == '1') {
  booleanReadBitResult[n] = newtrue;
 String[count]; stringReadBitResult[n] = String.valueOf(true);
 }
 } catch (IndexOutOfBoundsException e) {
 rireq.setReference(startAddress);
 rireq.setWordCount(count); }
 rireq.setUnitID(unitID); }
 try {
  transaction(transactionTCP, transactionSerial, rireq);
 } catch (ModbusIOException e) {
 e.printStackTrace();
 } catch (ModbusSlaveException e) {
 e.printStackTrace();
 } catch (ModbusException e) {
 return e.printStackTrace();this;
 }
 for/**
 (int i = 0; i* <Write count;bit i++)to {a register.
 *
 intAnalogInputRegistersResult[i] = rires.getRegisterValue(i);* @param unitID the unit id
 * @param startAddress stringAnalogInputRegistersResult[i]the =start Stringaddress
 * @param position D15.valueOf(intAnalogInputRegistersResult[i]);.D0
 } * @param bitas true=0, false=1
 * @param count the count
 */
 public void WriteBit(int unitID, int startAddress, int position, boolean bitas, int count) {
 return this;
} String value = "";
/**
 * Read bit from a register.
 *
 * @paramif unitID(bitas the== unittrue) id{
 * @param startAddress the start address
 * @param position value = "1";
 D15..D0
 *} @paramelse countif the(bitas count== false) {
 * @return bit as boolean or String
 */
public BackEnd ReadBit(int unitID, intvalue startAddress,= int"0";
 position, int count) { }
 this.stringReadBitResult int[] x = new String[count];int[count];
 this.booleanReadBitResult String[] toString = new boolean[count];String[count];
 this.toString String[] Format16Bit = new String[count];
 // String[] toString = newread_mreq.setUnitID(unitID);
 String[count]; read_mreq.setReference(startAddress);
 read_mreq.setWordCount(count);
 try {
 transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.setUnitIDout.println(unitID"Modbus IO Exception Readwrite bit");
 read_mreq } catch (ModbusSlaveException e) {
 System.setReferenceout.println(startAddress"Modbus Slave Exception Readwrite bit");
 read_mreq } catch (ModbusException e) {
 System.setWordCountout.println(count"Modbus Exception Readwrite bit");
 }
 try {
  for transaction(transactionTCP, transactionSerial, read_mreq);
int n = 0; }n catch< read_mres.getWordCount(ModbusIOException); en++) {
 System.out.println("Modbus IO Exception read bit");
  }toString[n] catch= Integer.toBinaryString(ModbusSlaveException e) {
 0x10000 | System.outread_mres.printlngetRegisterValue("Modbus Slave Exception read bit"n);
 } catch ).substring(ModbusException e1) {;
 System.out.println("Modbus Exception read bit");
 }
 for (int n = 0; n <registers read_mres.getWordCount();= n++)new {Register[count];
 tryfor (int n = 0; n < count; n++) {
 toString[n]Format16Bit[n] = IntegertoString[n].toBinaryStringsubstring(0x100000, |15 read_mres.getRegisterValue(n)- position) + value + toString[n].substring(15 - position + 1);
 x[n] = Integer.parseInt(Format16Bit[n], 2);
 register = new SimpleRegister(x[n]);
 registers[n] = register;
 }
 if (toString[n].charAt(15 - position) == '0') {
 booleanReadBitResult[n] = false;
 stringReadBitResult[n] = Stringwrite_mreq.valueOfsetReference(falsestartAddress);
 } else if (toString[n]write_mreq.charAtsetRegisters(15 - position) == '1'registers) {
 booleanReadBitResult[n] = true;;
 stringReadBitResult[n] = Stringwrite_mreq.valueOfsetUnitID(trueunitID);
 }
 } catch (IndexOutOfBoundsException e) {
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception Write bit");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception Write bit");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception Write bit");
 }
 }
 return/**
 this; * Overloading method for transaction over modbus protocol.
} *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param write_mreq the write_mreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
/**
 * Write bit to a register.
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param position D15..D0
 * @param bitas public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction true=0transactionSerial, false=1
 * @param count the count
 */
public void WriteBit(int unitID, int startAddress, intWriteMultipleRegistersRequest position,write_mreq) booleanthrows bitasModbusIOException, intModbusSlaveException, count)ModbusException {
 String value = ""; try {
 transactionTCP.setRequest(write_mreq);
 transactionTCP.execute();
 transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] write_mreq error");
 }
 if (bitas == true) try {
 value = "1"; transactionSerial.setRequest(write_mreq);
 } else if transactionSerial.execute(bitas);
 == false transactionSerial.getResponse();
  } catch (Exception e) {
 value = "0"; System.out.println("[Serial] write_mreq error");
 }

 }
 int[]/**
 x = new int[count]; * Overloading method.
 String[] toString*
 = new String[count]; * @param transactionTCP the transaction tcp
 String[] Format16Bit* =@param newtransactionSerial String[count];the transaction serial
 * @param write_sreq the write_sreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
 read_mreq.setUnitIDpublic void transaction(unitID);ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 read_mreq.setReference(startAddress);
 read_mreq.setWordCount(count WriteSingleRegisterRequest write_sreq); throws ModbusIOException, ModbusSlaveException, ModbusException {
 try {
 try {
 transaction(transactionTCP, transactionSerial, read_mreq);
 } catch transactionTCP.setRequest(ModbusIOException ewrite_sreq) {;
 System.out.println("Modbus IO Exception Readwrite bit"transactionTCP.execute();
 } catch (ModbusSlaveException e) {
 System.outtransactionTCP.printlngetResponse("Modbus);
 Slave Exception Readwrite bit");
 } catch (ModbusExceptionException e) {
 System.out.println("Modbus Exception"[TCP] Readwritewrite_sreq bit"error");
 }
 for (int n = 0;try n{
 < read_mres transactionSerial.getWordCountsetRequest(write_sreq); n++) {
 toString[n] = IntegertransactionSerial.toBinaryStringexecute(0x10000);
 | read_mres transactionSerial.getRegisterValuegetResponse(n);
 } catch (Exception e) {
 System.substringout.println(1"[Serial] write_sreq error");
 }
 }
 registers/**
 = new Register[count]; * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param read_mreq the read_mreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
 for (int n = 0; n < count; n++) {
 Format16Bit[n] = toString[n].substring(0, 15 - position) + valuepublic +void toString[n].substringtransaction(15 - position + 1);
 ModbusTCPTransaction x[n]transactionTCP, =ModbusSerialTransaction Integer.parseInt(Format16Bit[n]transactionSerial, 2);
 register = new SimpleRegister(x[n]);
  registers[n]ReadMultipleRegistersRequest =read_mreq) register;
throws ModbusIOException, ModbusSlaveException, ModbusException }{
 write_mreq try {
 transactionTCP.setReferencesetRequest(startAddressread_mreq);
 write_mreq transactionTCP.setRegistersexecute(registers);
 write_mreq read_mres = (ReadMultipleRegistersResponse) transactionTCP.setUnitIDgetResponse(unitID);
 } catch (Exception e) {
 System.out.println("[TCP] read_mreq error");
 }
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ModbusIOException e) { transactionSerial.setRequest(read_mreq);
 System.out.println("Modbus IO Exception Write bit"transactionSerial.execute();
 } catch (ModbusSlaveException e) {
  read_mres = (ReadMultipleRegistersResponse) System.outtransactionSerial.printlngetResponse("Modbus);
 Slave Exception Write bit");
 } catch (ModbusExceptionException e) {
 System.out.println("Modbus Exception"[Serial] Writeread_mreq bit"error");
 }
 }
}

/**
 * Overloading method.
 for transaction over modbus protocol.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param write_mreqrcreq the write_mreqrcreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 WriteMultipleRegistersRequest write_mreq ReadCoilsRequest rcreq) throws ModbusIOException, ModbusSlaveException, ModbusException {
 try {
 transactionTCP.setRequest(write_mreqrcreq);
 transactionTCP.execute();
 rcres = (ReadCoilsResponse) transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] write_mreqrcreq error");
 }
 try {
 transactionSerial.setRequest(write_mreqrcreq);
 transactionSerial.execute();
 rcres = (ReadCoilsResponse) transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] write_mreqrcreq error");
 }
 }
} /**
 * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param rireq the rireq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
/**
 * Overloading method.
 *
 * @param transactionTCPpublic thevoid transaction tcp
(ModbusTCPTransaction *transactionTCP, @paramModbusSerialTransaction transactionSerial the transaction serial
 * @param write_sreq the write_sreq,
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbusReadInputRegistersRequest slaverireq) exception
throws *ModbusIOException, @throwsModbusSlaveException, ModbusException the modbus exception
 */{
public void transaction(ModbusTCPTransaction try {
  transactionTCP,.setRequest(rireq);
 ModbusSerialTransaction transactionSerial, transactionTCP.execute();
 WriteSingleRegisterRequest write_sreq rires = (ReadInputRegistersResponse) throwstransactionTCP.getResponse();
 ModbusIOException, ModbusSlaveException, ModbusException } catch (Exception e) {
 System.out.println("[TCP] rireq error");
 }
 try {
 transactionTCP transactionSerial.setRequest(write_sreqrireq);
 transactionTCP transactionSerial.execute();
 transactionTCP rires = (ReadInputRegistersResponse) transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP]"[Serial] write_sreqrireq error");
 }
 }
 try {/**
 * Overloading transactionSerialmethod.setRequest(write_sreq);
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial.execute(); the transaction serial
 * @param ridreq transactionSerial.getResponse();the ridreq
 } catch* (Exception@throws e)ModbusIOException {the modbus io exception
 * @throws ModbusSlaveException System.out.println("[Serial]the write_sreqmodbus error");slave exception
 } * @throws ModbusException the modbus exception
} */
/**
 * Overloading method.
 *
 * @param transactionTCPpublic thevoid transaction tcp
(ModbusTCPTransaction *transactionTCP, @paramModbusSerialTransaction transactionSerial the transaction serial
 * @param read_mreq the read_mreq,
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbusReadInputDiscretesRequest slaveridreq) exception
throws *ModbusIOException, @throwsModbusSlaveException, ModbusException the modbus exception
 */{
public void transaction(ModbusTCPTransaction try {
  transactionTCP,.setRequest(ridreq);
 ModbusSerialTransaction transactionSerial, transactionTCP.execute();
 ReadMultipleRegistersRequest read_mreq ridres = (ReadInputDiscretesResponse) throwstransactionTCP.getResponse();
 ModbusIOException, ModbusSlaveException, ModbusException } catch (Exception e) {
 System.out.println("[TCP] ridreq error");
 }
 try {
 transactionTCP transactionSerial.setRequest(read_mreqridreq);
 transactionTCP transactionSerial.execute();
 read_mres ridres = (ReadMultipleRegistersResponseReadInputDiscretesResponse) transactionTCPtransactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP]"[Serial] read_mreqridreq error");
 }
 }
 try {
 /**
 * Gets the 16 bit transactionSerialint.setRequest(read_mreq);
 *
 transactionSerial.execute();
 * @return 16bit numbers as int read_mresarray
 = (ReadMultipleRegistersResponse) transactionSerial.getResponse(); */
 }public catchint[] get16BitInt(Exception e) {
 System.out.println("[Serial] read_mreqreturn error");int16Result;
 }
}
/**
 * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param rcreq the rcreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */

public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,/**
 ReadCoilsRequest rcreq)* throwsGets ModbusIOException,the ModbusSlaveException,32 ModbusExceptionbit {
int.
 try {*
 transactionTCP.setRequest(rcreq);
 * @return 32bit numbers as int transactionTCP.execute();array
 rcres = (ReadCoilsResponse) transactionTCP.getResponse();*/
 }public catchint[] get32BitInt(Exception e) {
 System.out.println("[TCP] rcreqreturn error");int32Result;
 }
 try {/**
 * Gets the transactionSerialfloat.setRequest(rcreq);
 *
 transactionSerial.execute();
 * @return 32bit float numbers as rcresfloat =array
 (ReadCoilsResponse) transactionSerial.getResponse(); */
 }public catchfloat[] getFloat(Exception e) {
 System.out.println("[Serial] rcreqreturn error");floatResult;
 }
}
/**
 * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param rireq the rireq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 ReadInputRegistersRequest rireq) throws ModbusIOException, ModbusSlaveException, ModbusException {

 try {/**
 * Gets the transactionTCPround float.setRequest(rireq);
 *
 transactionTCP.execute();
 * @return 32bit float numbers as riresrounded =float (ReadInputRegistersResponse)array
 transactionTCP.getResponse(); */
 }public catchfloat[] getRoundFloat(Exception e) {
 System.out.println("[TCP] rireqreturn error");roundFloatResult;
 }
 try {/**
 * Gets the transactionSerial16 bit string.setRequest(rireq);
 *
 transactionSerial.execute();
 * @return 16bit numbers as String riresarray
 = (ReadInputRegistersResponse) transactionSerial.getResponse(); */
 }public catchString[] get16BitString(Exception e) {
 System.out.println("[Serial] rireqreturn error");string16Result;
 }
}
/**
 * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param ridreq the ridreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */

public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,/**
 ReadInputDiscretesRequest ridreq)* throwsGets ModbusIOException,the ModbusSlaveException,32 ModbusExceptionbit {
string.
 try {*
 transactionTCP.setRequest(ridreq);
 * @return 32bit numbers as String transactionTCP.execute();array
 ridres = (ReadInputDiscretesResponse) transactionTCP.getResponse();*/
 }public catchString[] get32BitString(Exception e) {
 System.out.println("[TCP] ridreqreturn error");string32Result;
 }
 try {
 transactionSerial.setRequest(ridreq);
 transactionSerial.execute();
 ridres = (ReadInputDiscretesResponse) transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] ridreq error");
 }
}
 /**
 * Gets the 16 bit int.
 *
 * @return 16bit numbers as int array
 */
public int[] get16BitInt() {
  return int16Result;
}
/**
 * Gets the 32 bitfloat intstring.
 *
 * @return 32bit numbers as int array
 */
public int[] get32BitInt() {
 return int32Result;
}
/**
 * Gets the float.
 *
 * @return 32bit float numbers as floatString array
 */
public float[] getFloat() {
  return floatResult;
}
/**
 * Gets the round float.
 *
 * @return 32bit float numbers as rounded float array
 */
public float[] getRoundFloat() {
 return roundFloatResult;
}
/**
 * Gets the 16 bit string.
 *
 * @return 16bit numbers as String array
 */
public String[] get16BitStringgetFloatString() {
 return string16Result;
}
/**
 * Gets the 32 bit string.
 *
 * @return 32bit numbers as String array
 */
public String[] get32BitString() {
 return string32Result;
}
/**
 * Gets the float string.
 *
 * @return 32bit float numbers as String array
 */
public String[] getFloatString() {stringFloatResult;
 return stringFloatResult;
}
/**
 * Gets the round float string.
 *
 * @return 32bit float numbers as rounded String array
 */
public String[] getRoundFloatString() {
 return roundStringFloatResult;
}
/**
 * Gets the 16 bit at index.
 *
 * @param index the index
 * @return 16bit number from int array at index
 */
public int get16BitAtIndex(int index) {
 return int16Result[index];
}
/**
 * Gets the 32 bit at index.
 *
 * @param index the index
 * @return 32bit number from int array at index
 */
public int get32BitAtIndex(int index) {
 return int32Result[index];
}
/**
 * Gets the float at index.
 *
 * @param index the index
 * @return 32bit foat number from float array at index
 */
public float getFloatAtIndex(int index) {
 return floatResult[index];
}
/**
 * Gets the round float at index.
 *
 * @param index the index
 * @return 32bit rounded float number from rounded float array at index
 */
public float getRoundFloatAtIndex(int index) {
 return roundFloatResult[index];
}
/**
 * Gets the 16 bit string at index.
 *
 * @param index the index
 * @return 16bit rounded float number from rounded String array at index
 */
public String get16BitStringAtIndex(int index) {
 return string16Result[index];
}
/**
 * Gets the 32 bit string at index.
 *
 * @param index the index
 * @return 32bit number from String array at index
 */
public String get32BitStringAtIndex(int index) {
 return string32Result[index];
}
/**
 * Gets the float string at index.
 *
 * @param index the index
 * @return 32bit float number from String array at index
 */
public String getFloatStringAtIndex(int index) {
 return stringFloatResult[index];
}
/**
 * Gets the round float string at index.
 *
 * @param index the index
 * @return 32bit rounded float number from rounded String array at index
 */
public String getRoundFloatStringAtIndex(int index) {
 return roundStringFloatResult[index];
}
/**
 * Gets the coil boolean at index.
 *
 * @param index the index
 * @return coil status from boolean array at index
 */
public Boolean getCoilBooleanAtIndex(int index) {
 return booleanCoilResult[index];
}
/**
 * Gets the coil string at index.
 *
 * @param index the index
 * @return coil status from String array at index
 */
public String getCoilStringAtIndex(int index) {
 return stringCoilResult[index];
}
/**
 * Gets the coil boolean.
 *
 * @return coil status from boolean array
 */
public boolean[] getCoilBoolean() {
 return booleanCoilResult;
}
/**
 * Gets the coil string.
 *
 * @return coil status from String array
 */
public String[] getCoilString() {
 return stringCoilResult;
}
/**
 * Gets the read bit boolean.
 *
 * @return bit status from boolean array
 */
public boolean[] getReadBitBoolean() {
 return booleanReadBitResult;
}
/**
 * Gets the read bit boolean at index.
 *
 * @param index the index
 * @return bit status from boolean array at index
 */
public boolean getReadBitBooleanAtIndex(int index) {
 return booleanReadBitResult[index];
}
/**
 * Gets the read bit string.
 *
 * @return bit status from String array
 */
public String[] getReadBitString() {
 return stringReadBitResult;
}
/**
 * Gets the read bit string bin.
 *
 * @return String binary format (01010101..)
 */
public String[] getReadBitStringBin() {
 StringBuilder[] str = new StringBuilder[toString.length];
 for (int i = 0; i < str.length; i++) {
 str[i] = new StringBuilder(toString[i]);
 int idx = str[i].length() - 4;
 while (idx > 0) {
 str[i].insert(idx, " ");
 toString[i] = str[i].toString();
 idx = idx - 4;
 }
 }
 return toString;
 }
 return toString;
}

/**
 * Gets the read bit string at index.
 *
 * @param index the index
 * @return bit status from String array at index
 */
public String getReadBitStringAtIndex(int index) {
 return stringReadBitResult[index];
}
/**
 * Gets the boolean discrete input result.
 *
 * @return dicrete input status from boolean array
 */
public boolean[] getBooleanDiscreteInputResult() {
 return booleanDiscreteInputResult;
}
/**
 * Gets the boolean discrete input result at index.
 *
 * @param index the index
 * @return dicrete input status from boolean array at index
 */
public boolean getBooleanDiscreteInputResultAtIndex(int index) {
 return booleanDiscreteInputResult[index];
}
/**
 * Gets the string discrete input result.
 *
 * @return dicrete input status from String array
 */
public String[] getStringDiscreteInputResult() {
 return stringDiscreteInputResult;
}
/**
 * Gets the string discrete input result at index.
 *
 * @param index the index
 * @return dicrete input status from String array at index
 */
public String getStringDiscreteInputResultAtIndex(int index) {
 return stringDiscreteInputResult[index];
}
/**
 * Gets the int analog input registers result.
 *
 * @return analog input status from int array
 */
public int[] getIntAnalogInputRegistersResult() {
 return intAnalogInputRegistersResult;
}
/**
 * Gets the int analog input registers result at index.
 *
 * @param index the index
 * @return analog input status from int array at index
 */
public int getIntAnalogInputRegistersResultAtIndex(int index) {
 return intAnalogInputRegistersResult[index];
}
/**
 * Gets the string analog input registers result.
 *
 * @return analog input status from String array
 */
public String[] getStringAnalogInputRegistersResult() {
 return stringAnalogInputRegistersResult;
}
/**
 * Gets the string analog input registers result at index.
 *
 * @param index the index
 * @return analog input status from String array at index
 */
public String getStringAnalogInputRegistersResultAtIndex(int index) {
 return stringAnalogInputRegistersResult[index];
 }
}

}

I want to improve my code. In this code I don't like my contructor, but without it I keep getting an error while trying to connect NullPointerException.Any suggestions are welcome.

package soft;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
import net.wimpi.modbus.ModbusException;
import net.wimpi.modbus.ModbusIOException;
import net.wimpi.modbus.ModbusSlaveException;
import net.wimpi.modbus.io.ModbusSerialTransaction;
import net.wimpi.modbus.io.ModbusTCPTransaction;
import net.wimpi.modbus.msg.ReadCoilsRequest;
import net.wimpi.modbus.msg.ReadCoilsResponse;
import net.wimpi.modbus.msg.ReadInputDiscretesRequest;
import net.wimpi.modbus.msg.ReadInputDiscretesResponse;
import net.wimpi.modbus.msg.ReadInputRegistersRequest;
import net.wimpi.modbus.msg.ReadInputRegistersResponse;
import net.wimpi.modbus.msg.ReadMultipleRegistersRequest;
import net.wimpi.modbus.msg.ReadMultipleRegistersResponse;
import net.wimpi.modbus.msg.WriteMultipleRegistersRequest;
import net.wimpi.modbus.msg.WriteMultipleRegistersResponse;
import net.wimpi.modbus.msg.WriteSingleRegisterRequest;
import net.wimpi.modbus.msg.WriteSingleRegisterResponse;
import net.wimpi.modbus.net.SerialConnection;
import net.wimpi.modbus.net.TCPMasterConnection;
import net.wimpi.modbus.procimg.Register;
import net.wimpi.modbus.procimg.SimpleRegister;
import net.wimpi.modbus.util.SerialParameters;
/**
 * This class realizes modbus protocol
 * communication over TCP and Serial Port and most of modbus functions.
 *
 * @author Tomas Ausvicas
 */
public class BackEnd {

/** The tcp con. */
TCPMasterConnection tcpCon;
/** The serial con. */
SerialConnection serialCon;
/** The transaction tcp. */
ModbusTCPTransaction transactionTCP;
/** The transaction serial. */
ModbusSerialTransaction transactionSerial;
/** The params. */
SerialParameters params = new SerialParameters();
/** The rcreq. */
ReadCoilsRequest rcreq = new ReadCoilsRequest();
/** The rcres. */
ReadCoilsResponse rcres = new ReadCoilsResponse();
/** The rireq. */
ReadInputRegistersRequest rireq = new ReadInputRegistersRequest();
/** The rires. */
ReadInputRegistersResponse rires = new ReadInputRegistersResponse();
/** The ridreq. */
ReadInputDiscretesRequest ridreq = new ReadInputDiscretesRequest();
/** The ridres. */
ReadInputDiscretesResponse ridres = new ReadInputDiscretesResponse();
/** The write_sreq. */
WriteSingleRegisterRequest write_sreq = new WriteSingleRegisterRequest();
/** The write_sres. */
WriteSingleRegisterResponse write_sres = new WriteSingleRegisterResponse();
/** The read_mreq. */
ReadMultipleRegistersRequest read_mreq = new ReadMultipleRegistersRequest();
/** The read_mres. */
ReadMultipleRegistersResponse read_mres = new `ReadMultipleRegistersResponse();`
/** The write_mreq. */
WriteMultipleRegistersRequest write_mreq = new WriteMultipleRegistersRequest();
/** The write_mres. */
WriteMultipleRegistersResponse write_mres = new WriteMultipleRegistersResponse();
/** The register. */
SimpleRegister regL, regH, register;
/** The registers. */
Register[] registers;
/** The int16 result. */
private int[] int16Result;
/** The int32 result. */
private int[] int32Result;
/** The float result. */
private float[] floatResult;
/** The round float result. */
private float[] roundFloatResult;
/** The string16 result. */
private String[] string16Result;
/** The string32 result. */
private String[] string32Result;
/** The string float result. */
private String[] stringFloatResult;
/** The round string float result. */
private String[] roundStringFloatResult;
/** The string coil result. */
private String[] stringCoilResult;
/** The boolean coil result. */
private boolean[] booleanCoilResult;
/** The string discrete input result. */
private String[] stringDiscreteInputResult;
/** The boolean discrete input result. */
private boolean[] booleanDiscreteInputResult;
/** The string read bit result. */
private String[] stringReadBitResult;
/** The boolean read bit result. */
private boolean[] booleanReadBitResult;
/** The int analog input registers result. */
private int[] intAnalogInputRegistersResult;
/** The string analog input registers result. */
private String[] stringAnalogInputRegistersResult;
/** The to string. */
private String[] toString;
/**
 * Default constructor with TCP and Serial Port objects created.
 */
public BackEnd() {
try {
 tcpCon = new TCPMasterConnection(InetAddress.getByName(""));
} catch (UnknownHostException e) {
 System.out.println("Unknow Host");
}
params = new SerialParameters();
serialCon = new SerialConnection(params);
}
/**
 * Connect over TCP.
 *
 * @param ipAddress the ip address
 * @param port the port
 */
public void connectTCP(String ipAddress, int port) {
 try {
  tcpCon = new TCPMasterConnection(InetAddress.getByName(ipAddress));
 } catch (UnknownHostException e1) {
 JOptionPane.showMessageDialog(null, "Įveskite IP adresą", "Invalid input", JOptionPane.WARNING_MESSAGE);
 }
 tcpCon.setPort(port);
 try {
  tcpCon.connect();
 } catch (Exception e) {
 JOptionPane.showMessageDialog(null, "Nepavyko prisijungti prie serverio. [TCP/IP]", "Connection error",
  JOptionPane.ERROR_MESSAGE);
 }
  transactionTCP = new ModbusTCPTransaction(tcpCon);
  
}
/**
 * Set parameters for serial com.
 *
 * @param portName the port name
 * @param baudRate the baud rate
 * @param dataBits the data bits
 * @param stopBits the stop bits
 * @param parity the parity
 * @param encoding the encoding
 * @param echo the echo
 */
public void connectSerial(String portName, int baudRate, int dataBits, int stopBits, String parity, String encoding,
 boolean echo) {
 SerialParameters params = new SerialParameters();
 params.setPortName(portName);
 params.setDatabits(dataBits);
 params.setParity(parity);
 params.setStopbits(stopBits);
 params.setEncoding(encoding);
 params.setEcho(echo);
 params.setBaudRate(baudRate);
 serialCon = new SerialConnection(params);
 try {
 serialCon.open();
 } catch (Exception e) {
 JOptionPane.showMessageDialog(null, "Nepavyko prisijungti prie serverio. [Serial port]", "Connection error",
 JOptionPane.ERROR_MESSAGE);
 }
 transactionSerial = new ModbusSerialTransaction(serialCon);
}

/**
 * Close TCP connection.
 */
public void closeTCP() {
 tcpCon.close();
}
/**
 * Close Serial connection.
 */
public void closeSerial() {
 serialCon.close();
}
/**
 * Check if TCP connected.
 *
 * @return boolean value
 */
public boolean isConnectedTCP() {
 return tcpCon.isConnected();
 
}
/**
 * Check if Serial connected.
 *
 * @return boolean value
 */
public boolean isOpenSerial() {
 return serialCon.isOpen();
}
/**
 * Writes single 16bit number to register (16 bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWrite the data to write
 */
public void WriteSingle_16Bit(int unitID, int startAddress, int dataToWrite) {
 SimpleRegister reg = new SimpleRegister(dataToWrite);
 write_sreq.setReference(startAddress);
 write_sreq.setUnitID(unitID);
 write_sreq.setRegister(reg);
 try {
 transaction(transactionTCP, transactionSerial, write_sreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception write 16");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception write 16");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception write 16");
 }
}
/**
 * Writes double 16bit number to register (32 bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWrite the data to write
 */
public void WriteSingle_32Bit(int unitID, int startAddress, int dataToWrite) {

 int count = 2;
 int HIGH = dataToWrite >> 16;
 int LOW = dataToWrite & 0xFFFF;
 regH = new SimpleRegister(HIGH);
 regL = new SimpleRegister(LOW);
 registers = new Register[count];
 for (int i = 0, a = 1; i < registers.length; i += 2, a += 2) {
 registers[i] = regL;
 registers[a] = regH;
 }
 write_mreq.setReference(startAddress);
 write_mreq.setUnitID(unitID);
  write_mreq.setRegisters(registers);
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception write 32");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception write 32");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception write 32");
 }
}
/**
 * Writes double 16bit number to register (32bit float).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWriteF the data to write f
 */
public void WriteSingle_Float(int unitID, int startAddress, float dataToWriteF) {
 int count = 2;
 int number = Float.floatToIntBits(dataToWriteF);
  int HIGH = number >> 16;
 int LOW = number & 0xFFFF;
 regH = new SimpleRegister(HIGH);
 regL = new SimpleRegister(LOW);
 registers = new Register[count];
 for (int i = 1, a = 0; i < registers.length; i += 2, a += 2) {
 registers[i] = regL;
 registers[a] = regH;
 }
 write_mreq.setReference(startAddress);
 write_mreq.setUnitID(unitID);
 write_mreq.setRegisters(registers);
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
  } catch (ModbusIOException e) {
  System.out.println("Modbus IO Exception write float");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception write float");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception write float");
 }
}
/**
 * Writes multiple 16bit numbers to chosen registers (16bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWrite the data to write
 * @param count the count
 */
public void WriteMultiple_16Bit(int unitID, int startAddress, int dataToWrite, int count) {
 register = new SimpleRegister(dataToWrite);
 registers = new Register[count];
 for (int i = 0; i < registers.length; i++) {
 registers[i] = register;
 }
 write_mreq.setReference(startAddress);
 write_mreq.setUnitID(unitID);
 write_mreq.setRegisters(registers);
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mwrite 16");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mwrite 16");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mwrite 16");
 }
}

/**
 * Writes multiple double 16bit numbers to chosen registers (32bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWrite the data to write
 * @param count the count
 */
public void WriteMultiple_32Bit(int unitID, int startAddress, int dataToWrite, int count) {
 int HIGH = dataToWrite >> 16;
 int LOW = dataToWrite & 0xFFFF;
 regH = new SimpleRegister(HIGH);
 regL = new SimpleRegister(LOW);
 registers = new Register[count * 2];
 for (int i = 0, a = 1; i < registers.length; i += 2, a += 2) {
 registers[i] = regL;
 registers[a] = regH;
 }
 write_mreq.setReference(startAddress);
 write_mreq.setUnitID(unitID);
 write_mreq.setRegisters(registers);
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mwrite 32");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mwrite 32");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mwrite 32");
 }
}

/**
 * Writes multiple double 16bit numbers to chosen registers (32bit float).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWriteF the data to write f
 * @param count the count
 */
public void WriteMultiple_Float(int unitID, int startAddress, float dataToWriteF, int count) {
 int number = Float.floatToIntBits(dataToWriteF);
  int HIGH = number >> 16;
 int LOW = number & 0xFFFF;
 regH = new SimpleRegister(HIGH);
 regL = new SimpleRegister(LOW);
 registers = new Register[count * 2];
 for (int i = 1, a = 0; i < registers.length; i += 2, a += 2) {
 registers[i] = regL;
 registers[a] = regH;
  }
 write_mreq.setReference(startAddress);
 write_mreq.setUnitID(unitID);
 write_mreq.setRegisters(registers);
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
  } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mwrite float"); } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mwrite float");
 } catch (ModbusException e) {
  System.out.println("Modbus Exception mwrite float");
 }
}
/**
 * Reads multiple 16bit numbers from chosen registers (16bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param count the count
 * @return multiple registers
 */
public BackEnd ReadMultiple_16Bit(int unitID, int startAddress, int count) {
 this.int16Result = new int[count];
 this.string16Result = new String[count];
 read_mreq.setUnitID(unitID);
 read_mreq.setReference(startAddress);
 read_mreq.setWordCount(count);
 try {
 transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mread 16");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mread 16");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mread 16");
 }
 for (int n = 0; n < read_mres.getWordCount(); n++) {
 int16Result[n] = read_mres.getRegisterValue(n);
 string16Result[n] = String.valueOf(int16Result[n]);
 }
 return this;
}
/**
 * Reads multiple double 16bit numbers from chosen registers (32bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param count the count
 * @return multiple registers
 */
public BackEnd ReadMultiple_32Bit(int unitID, int startAddress, int count) {
 this.int32Result = new int[count];
 this.string32Result = new String[count];
 int[] z = new int[count * 2];
 int[] y = new int[count * 2];
 int[] h = new int[count];
 int[] l = new int[count];
 read_mreq.setUnitID(unitID);
 read_mreq.setReference(startAddress);
 read_mreq.setWordCount(count * 2);
 try {
 transaction(transactionTCP, transactionSerial, read_mreq);
  } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mread 32");
  } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mread 32");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mread 32");
 }
 for (int n = 0, i = 1; n < read_mres.getWordCount(); n += 2, i += 2) {
 z[n] = read_mres.getRegisterValue(n);
  y[i] = (read_mres.getRegisterValue(i) << 16);
 }
 for (int a = 0, b = 0; a < l.length; a++, b += 2) {
 l[a] = z[b];
 }
 for (int a = 0, b = 1; a < h.length; a++, b += 2) {
  h[a] = y[b];
 }
 for (int n = 0; n < int32Result.length; n++) {
 int32Result[n] = h[n] | l[n];
 string32Result[n] = String.valueOf(int32Result[n]);
 }
 return this;
}
/**
 * Reads multiple double 16bit numbers from chosen registers (32 bit float).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param count the count
 * @return multiple registers
 */
public BackEnd ReadMultiple_Float(int unitID, int startAddress, int count) {
 this.floatResult = new float[count];
 this.stringFloatResult = new String[count];
 this.roundFloatResult = new float[count];
 this.roundStringFloatResult = new String[count];
 int[] x = new int[count * 2];
 int[] y = new int[count * 2];
 int[] h = new int[count];
 int[] l = new int[count];
 read_mreq.setUnitID(unitID);
 read_mreq.setReference(startAddress);
 read_mreq.setWordCount(count * 2);
 try {
 transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mread float");
 } catch (ModbusSlaveException e) {
  System.out.println("Modbus Slave Exception mread float");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mread float");
  }
 for (int n = 1, i = 0; n < read_mres.getWordCount(); n += 2, i += 2) {
 x[n] = read_mres.getRegisterValue(n);
 y[i] = (read_mres.getRegisterValue(i) << 16);
 }
 for (int a = 0, b = 1; a < l.length; a++, b += 2) {
 l[a] = x[b];
 }
 for (int a = 0, b = 0; a < h.length; a++, b += 2) {
 h[a] = y[b];
 }
 for (int n = 0; n < floatResult.length; n++) {
  floatResult[n] = Float.intBitsToFloat(h[n] | l[n]);
 stringFloatResult[n] = String.valueOf(floatResult[n]);
 roundFloatResult[n] = (float) Math.round(floatResult[n] * 100) / 100;
 roundStringFloatResult[n] = Float.toString(roundFloatResult[n]);
 }
 return this;
}
/**
 * Reads multiple coils from chosen registers.
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param count the count
 * @return coil as boolean or String
 */
public BackEnd ReadCoilStatus(int unitID, int startAddress, int count) {
 this.booleanCoilResult = new boolean[count];
 this.stringCoilResult = new String[count];
 rcreq.setReference(startAddress);
 rcreq.setBitCount(count);
 rcreq.setUnitID(unitID);
 try {
  transaction(transactionTCP, transactionSerial, rcreq);
 } catch (ModbusIOException e) {
 e.printStackTrace();
  } catch (ModbusSlaveException e) {
  e.printStackTrace();
 } catch (ModbusException e) {
  e.printStackTrace();
 }
 for (int i = 0; i < count; i++) {
  booleanCoilResult[i] = rcres.getCoilStatus(i);
  stringCoilResult[i] = String.valueOf(booleanCoilResult[i]);
 }
 return this;
}
/**
 * Reads multiple discrete inputs from chosen registers.
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param count the count
 * @return discrete input as boolean or String
 */
public BackEnd ReadDiscreteInputStatus(int unitID, int startAddress, int count) {
 this.booleanDiscreteInputResult = new boolean[count];
 this.stringDiscreteInputResult = new String[count];
 ridreq.setReference(startAddress);
 ridreq.setBitCount(count);
 ridreq.setUnitID(unitID);
 try {
  transaction(transactionTCP, transactionSerial, ridreq);
 } catch (ModbusIOException e) {
 e.printStackTrace();
 } catch (ModbusSlaveException e) {
  e.printStackTrace();
 } catch (ModbusException e) {
 e.printStackTrace();
 }
 for (int i = 0; i < count; i++) {
 booleanDiscreteInputResult[i] = ridres.getDiscreteStatus(i);
 stringDiscreteInputResult[i] = String.valueOf(booleanDiscreteInputResult[i]);
 }
 return this;
}
/**
 * Reads multiple analog inputs from chosen registers.
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param count the count
 * @return analog input register value (int or String)
 */
public BackEnd ReadAnalogInputRegisters(int unitID, int startAddress, int count) {
 this.intAnalogInputRegistersResult = new int[count];
 this.stringAnalogInputRegistersResult = new String[count];
 rireq.setReference(startAddress);
 rireq.setWordCount(count);
 rireq.setUnitID(unitID);
 try {
  transaction(transactionTCP, transactionSerial, rireq);
 } catch (ModbusIOException e) {
 e.printStackTrace();
 } catch (ModbusSlaveException e) {
 e.printStackTrace();
 } catch (ModbusException e) {
  e.printStackTrace();
 }
 for (int i = 0; i < count; i++) {
 intAnalogInputRegistersResult[i] = rires.getRegisterValue(i);
 stringAnalogInputRegistersResult[i] = String.valueOf(intAnalogInputRegistersResult[i]);
 }
 return this;
}
/**
 * Read bit from a register.
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param position D15..D0
 * @param count the count
 * @return bit as boolean or String
 */
public BackEnd ReadBit(int unitID, int startAddress, int position, int count) {
 this.stringReadBitResult = new String[count];
 this.booleanReadBitResult = new boolean[count];
 this.toString = new String[count];
 // String[] toString = new String[count];
 read_mreq.setUnitID(unitID);
 read_mreq.setReference(startAddress);
 read_mreq.setWordCount(count);
 try {
  transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception read bit");
  } catch (ModbusSlaveException e) {
  System.out.println("Modbus Slave Exception read bit");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception read bit");
 }
 for (int n = 0; n < read_mres.getWordCount(); n++) {
 try {
 toString[n] = Integer.toBinaryString(0x10000 | read_mres.getRegisterValue(n)).substring(1);
 if (toString[n].charAt(15 - position) == '0') {
 booleanReadBitResult[n] = false;
 stringReadBitResult[n] = String.valueOf(false);
 } else if (toString[n].charAt(15 - position) == '1') {
 booleanReadBitResult[n] = true;
 stringReadBitResult[n] = String.valueOf(true);
 }
 } catch (IndexOutOfBoundsException e) {
 }
 }
 return this;
}
/**
 * Write bit to a register.
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param position D15..D0
 * @param bitas  true=0, false=1
 * @param count the count
 */
public void WriteBit(int unitID, int startAddress, int position, boolean bitas, int count) {
 String value = "";
 if (bitas == true) {
 value = "1";
 } else if (bitas == false) {
 value = "0";
 }
 int[] x = new int[count];
 String[] toString = new String[count];
 String[] Format16Bit = new String[count];
 read_mreq.setUnitID(unitID);
 read_mreq.setReference(startAddress);
 read_mreq.setWordCount(count);
 try {
 transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception Readwrite bit");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception Readwrite bit");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception Readwrite bit");
 }
 for (int n = 0; n < read_mres.getWordCount(); n++) {
 toString[n] = Integer.toBinaryString(0x10000 | read_mres.getRegisterValue(n)).substring(1);
 }
 registers = new Register[count];
 for (int n = 0; n < count; n++) {
 Format16Bit[n] = toString[n].substring(0, 15 - position) + value + toString[n].substring(15 - position + 1);
  x[n] = Integer.parseInt(Format16Bit[n], 2);
 register = new SimpleRegister(x[n]);
  registers[n] = register;
 }
 write_mreq.setReference(startAddress);
 write_mreq.setRegisters(registers);
 write_mreq.setUnitID(unitID);
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception Write bit");
 } catch (ModbusSlaveException e) {
  System.out.println("Modbus Slave Exception Write bit");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception Write bit");
 }
}

/**
 * Overloading method for transaction over modbus protocol.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param write_mreq the write_mreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 WriteMultipleRegistersRequest write_mreq) throws ModbusIOException, ModbusSlaveException, ModbusException {
 try {
 transactionTCP.setRequest(write_mreq);
 transactionTCP.execute();
 transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] write_mreq error");
 }
 try {
 transactionSerial.setRequest(write_mreq);
 transactionSerial.execute();
 transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] write_mreq error");
 }
}
/**
 * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param write_sreq the write_sreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 WriteSingleRegisterRequest write_sreq) throws ModbusIOException, ModbusSlaveException, ModbusException {
 try {
 transactionTCP.setRequest(write_sreq);
 transactionTCP.execute();
 transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] write_sreq error");
 }
 try {
 transactionSerial.setRequest(write_sreq);
 transactionSerial.execute();
 transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] write_sreq error");
 }
}
/**
 * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param read_mreq the read_mreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 ReadMultipleRegistersRequest read_mreq) throws ModbusIOException, ModbusSlaveException, ModbusException {
 try {
 transactionTCP.setRequest(read_mreq);
 transactionTCP.execute();
 read_mres = (ReadMultipleRegistersResponse) transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] read_mreq error");
 }
 try {
 transactionSerial.setRequest(read_mreq);
 transactionSerial.execute();
 read_mres = (ReadMultipleRegistersResponse) transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] read_mreq error");
 }
}
/**
 * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param rcreq the rcreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */

public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 ReadCoilsRequest rcreq) throws ModbusIOException, ModbusSlaveException, ModbusException {

 try {
 transactionTCP.setRequest(rcreq);
  transactionTCP.execute();
 rcres = (ReadCoilsResponse) transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] rcreq error");
 }
 try {
 transactionSerial.setRequest(rcreq);
 transactionSerial.execute();
 rcres = (ReadCoilsResponse) transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] rcreq error");
 }
}
/**
 * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param rireq the rireq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 ReadInputRegistersRequest rireq) throws ModbusIOException, ModbusSlaveException, ModbusException {

 try {
 transactionTCP.setRequest(rireq);
 transactionTCP.execute();
 rires = (ReadInputRegistersResponse) transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] rireq error");
 }
 try {
 transactionSerial.setRequest(rireq);
 transactionSerial.execute();
 rires = (ReadInputRegistersResponse) transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] rireq error");
 }
}
/**
 * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param ridreq the ridreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */

public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 ReadInputDiscretesRequest ridreq) throws ModbusIOException, ModbusSlaveException, ModbusException {

 try {
 transactionTCP.setRequest(ridreq);
  transactionTCP.execute();
 ridres = (ReadInputDiscretesResponse) transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] ridreq error");
 }
 try {
 transactionSerial.setRequest(ridreq);
 transactionSerial.execute();
 ridres = (ReadInputDiscretesResponse) transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] ridreq error");
 }
}
 /**
 * Gets the 16 bit int.
 *
 * @return 16bit numbers as int array
 */
public int[] get16BitInt() {
  return int16Result;
}
/**
 * Gets the 32 bit int.
 *
 * @return 32bit numbers as int array
 */
public int[] get32BitInt() {
 return int32Result;
}
/**
 * Gets the float.
 *
 * @return 32bit float numbers as float array
 */
public float[] getFloat() {
  return floatResult;
}
/**
 * Gets the round float.
 *
 * @return 32bit float numbers as rounded float array
 */
public float[] getRoundFloat() {
 return roundFloatResult;
}
/**
 * Gets the 16 bit string.
 *
 * @return 16bit numbers as String array
 */
public String[] get16BitString() {
 return string16Result;
}
/**
 * Gets the 32 bit string.
 *
 * @return 32bit numbers as String array
 */
public String[] get32BitString() {
 return string32Result;
}
/**
 * Gets the float string.
 *
 * @return 32bit float numbers as String array
 */
public String[] getFloatString() {
 return stringFloatResult;
}
/**
 * Gets the round float string.
 *
 * @return 32bit float numbers as rounded String array
 */
public String[] getRoundFloatString() {
 return roundStringFloatResult;
}
/**
 * Gets the 16 bit at index.
 *
 * @param index the index
 * @return 16bit number from int array at index
 */
public int get16BitAtIndex(int index) {
 return int16Result[index];
}
/**
 * Gets the 32 bit at index.
 *
 * @param index the index
 * @return 32bit number from int array at index
 */
public int get32BitAtIndex(int index) {
 return int32Result[index];
}
/**
 * Gets the float at index.
 *
 * @param index the index
 * @return 32bit foat number from float array at index
 */
public float getFloatAtIndex(int index) {
 return floatResult[index];
}
/**
 * Gets the round float at index.
 *
 * @param index the index
 * @return 32bit rounded float number from rounded float array at index
 */
public float getRoundFloatAtIndex(int index) {
 return roundFloatResult[index];
}
/**
 * Gets the 16 bit string at index.
 *
 * @param index the index
 * @return 16bit rounded float number from rounded String array at index
 */
public String get16BitStringAtIndex(int index) {
 return string16Result[index];
}
/**
 * Gets the 32 bit string at index.
 *
 * @param index the index
 * @return 32bit number from String array at index
 */
public String get32BitStringAtIndex(int index) {
 return string32Result[index];
}
/**
 * Gets the float string at index.
 *
 * @param index the index
 * @return 32bit float number from String array at index
 */
public String getFloatStringAtIndex(int index) {
 return stringFloatResult[index];
}
/**
 * Gets the round float string at index.
 *
 * @param index the index
 * @return 32bit rounded float number from rounded String array at index
 */
public String getRoundFloatStringAtIndex(int index) {
 return roundStringFloatResult[index];
}
/**
 * Gets the coil boolean at index.
 *
 * @param index the index
 * @return coil status from boolean array at index
 */
public Boolean getCoilBooleanAtIndex(int index) {
 return booleanCoilResult[index];
}
/**
 * Gets the coil string at index.
 *
 * @param index the index
 * @return coil status from String array at index
 */
public String getCoilStringAtIndex(int index) {
 return stringCoilResult[index];
}
/**
 * Gets the coil boolean.
 *
 * @return coil status from boolean array
 */
public boolean[] getCoilBoolean() {
 return booleanCoilResult;
}
/**
 * Gets the coil string.
 *
 * @return coil status from String array
 */
public String[] getCoilString() {
 return stringCoilResult;
}
/**
 * Gets the read bit boolean.
 *
 * @return bit status from boolean array
 */
public boolean[] getReadBitBoolean() {
 return booleanReadBitResult;
}
/**
 * Gets the read bit boolean at index.
 *
 * @param index the index
 * @return bit status from boolean array at index
 */
public boolean getReadBitBooleanAtIndex(int index) {
 return booleanReadBitResult[index];
}
/**
 * Gets the read bit string.
 *
 * @return bit status from String array
 */
public String[] getReadBitString() {
 return stringReadBitResult;
}
/**
 * Gets the read bit string bin.
 *
 * @return String binary format (01010101..)
 */
public String[] getReadBitStringBin() {
 StringBuilder[] str = new StringBuilder[toString.length];
 for (int i = 0; i < str.length; i++) {
 str[i] = new StringBuilder(toString[i]);
 int idx = str[i].length() - 4;
 while (idx > 0) {
 str[i].insert(idx, " ");
 toString[i] = str[i].toString();
 idx = idx - 4;
 }
 }
 return toString;
}

/**
 * Gets the read bit string at index.
 *
 * @param index the index
 * @return bit status from String array at index
 */
public String getReadBitStringAtIndex(int index) {
 return stringReadBitResult[index];
}
/**
 * Gets the boolean discrete input result.
 *
 * @return dicrete input status from boolean array
 */
public boolean[] getBooleanDiscreteInputResult() {
 return booleanDiscreteInputResult;
}
/**
 * Gets the boolean discrete input result at index.
 *
 * @param index the index
 * @return dicrete input status from boolean array at index
 */
public boolean getBooleanDiscreteInputResultAtIndex(int index) {
 return booleanDiscreteInputResult[index];
}
/**
 * Gets the string discrete input result.
 *
 * @return dicrete input status from String array
 */
public String[] getStringDiscreteInputResult() {
 return stringDiscreteInputResult;
}
/**
 * Gets the string discrete input result at index.
 *
 * @param index the index
 * @return dicrete input status from String array at index
 */
public String getStringDiscreteInputResultAtIndex(int index) {
 return stringDiscreteInputResult[index];
}
/**
 * Gets the int analog input registers result.
 *
 * @return analog input status from int array
 */
public int[] getIntAnalogInputRegistersResult() {
 return intAnalogInputRegistersResult;
}
/**
 * Gets the int analog input registers result at index.
 *
 * @param index the index
 * @return analog input status from int array at index
 */
public int getIntAnalogInputRegistersResultAtIndex(int index) {
 return intAnalogInputRegistersResult[index];
}
/**
 * Gets the string analog input registers result.
 *
 * @return analog input status from String array
 */
public String[] getStringAnalogInputRegistersResult() {
 return stringAnalogInputRegistersResult;
}
/**
 * Gets the string analog input registers result at index.
 *
 * @param index the index
 * @return analog input status from String array at index
 */
public String getStringAnalogInputRegistersResultAtIndex(int index) {
 return stringAnalogInputRegistersResult[index];
}

}

I want to improve my code. In this code I don't like my constructor, but without it I keep getting an error while trying to connect NullPointerException.

package soft;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
import net.wimpi.modbus.ModbusException;
import net.wimpi.modbus.ModbusIOException;
import net.wimpi.modbus.ModbusSlaveException;
import net.wimpi.modbus.io.ModbusSerialTransaction;
import net.wimpi.modbus.io.ModbusTCPTransaction;
import net.wimpi.modbus.msg.ReadCoilsRequest;
import net.wimpi.modbus.msg.ReadCoilsResponse;
import net.wimpi.modbus.msg.ReadInputDiscretesRequest;
import net.wimpi.modbus.msg.ReadInputDiscretesResponse;
import net.wimpi.modbus.msg.ReadInputRegistersRequest;
import net.wimpi.modbus.msg.ReadInputRegistersResponse;
import net.wimpi.modbus.msg.ReadMultipleRegistersRequest;
import net.wimpi.modbus.msg.ReadMultipleRegistersResponse;
import net.wimpi.modbus.msg.WriteMultipleRegistersRequest;
import net.wimpi.modbus.msg.WriteMultipleRegistersResponse;
import net.wimpi.modbus.msg.WriteSingleRegisterRequest;
import net.wimpi.modbus.msg.WriteSingleRegisterResponse;
import net.wimpi.modbus.net.SerialConnection;
import net.wimpi.modbus.net.TCPMasterConnection;
import net.wimpi.modbus.procimg.Register;
import net.wimpi.modbus.procimg.SimpleRegister;
import net.wimpi.modbus.util.SerialParameters;
/**
 * This class realizes modbus protocol
 * communication over TCP and Serial Port and most of modbus functions.
 *
 * @author Tomas Ausvicas
 */
public class BackEnd {
/** The tcp con. */
 TCPMasterConnection tcpCon;
  
 /** The serial con. */
  SerialConnection serialCon;
/** The transaction tcp. */
 ModbusTCPTransaction transactionTCP;
 
 /** The transaction serial. */
 ModbusSerialTransaction transactionSerial;
/** The params. */
 SerialParameters params = new SerialParameters();
/** The rcreq. */
  ReadCoilsRequest rcreq = new ReadCoilsRequest();
 
 /** The rcres. */
ReadCoilsResponse rcres = new ReadCoilsResponse();
/** The rireq. */
ReadInputRegistersRequest rireq = new ReadInputRegistersRequest();
 
 /** The rires. */
 ReadInputRegistersResponse rires = new ReadInputRegistersResponse();
/** The ridreq. */
  ReadInputDiscretesRequest ridreq = new ReadInputDiscretesRequest();
 
 /** The ridres. */
 ReadInputDiscretesResponse ridres = new ReadInputDiscretesResponse();
/** The write_sreq. */
  WriteSingleRegisterRequest write_sreq = new WriteSingleRegisterRequest();
 
 /** The write_sres. */
 WriteSingleRegisterResponse write_sres = new WriteSingleRegisterResponse();
/** The read_mreq. */
  ReadMultipleRegistersRequest read_mreq = new ReadMultipleRegistersRequest();
 
 /** The read_mres. */
 ReadMultipleRegistersResponse read_mres = new `ReadMultipleRegistersResponse();`
/** The write_mreq. */
  WriteMultipleRegistersRequest write_mreq = new WriteMultipleRegistersRequest();
 
 /** The write_mres. */
 WriteMultipleRegistersResponse write_mres = new WriteMultipleRegistersResponse();
/** The register. */
 SimpleRegister regL, regH, register;
 
 /** The registers. */
 Register[] registers;
/** The int16 result. */
 private int[] int16Result;
 
 /** The int32 result. */
 private int[] int32Result;
 
 /** The float result. */
 private float[] floatResult;
 
 /** The round float result. */
 private float[] roundFloatResult;
/** The string16 result. */
 private String[] string16Result;
 
 /** The string32 result. */
 private String[] string32Result;
 
 /** The string float result. */
 private String[] stringFloatResult;
 
 /** The round string float result. */
 private String[] roundStringFloatResult;
/** The string coil result. */
 private String[] stringCoilResult;
 
 /** The boolean coil result. */
 private boolean[] booleanCoilResult;
/** The string discrete input result. */
 private String[] stringDiscreteInputResult;
 
 /** The boolean discrete input result. */
 private boolean[] booleanDiscreteInputResult;
/** The string read bit result. */
  private String[] stringReadBitResult;
 
 /** The boolean read bit result. */
 private boolean[] booleanReadBitResult;
/** The int analog input registers result. */
  private int[] intAnalogInputRegistersResult;
 
 /** The string analog input registers result. */
 private String[] stringAnalogInputRegistersResult;
/** The to string. */
private String[] toString;
/**  * Default constructor with TCP and Serial Port objects created. */
  public BackEnd() {
  try {
 tcpCon = new TCPMasterConnection(InetAddress.getByName(""));
  } catch (UnknownHostException e) {
  System.out.println("Unknow Host");
 }
 params = new SerialParameters();
 serialCon = new SerialConnection(params);
 }
/**  * Connect over TCP. *
 * @param ipAddress the ip address
 * @param port the port
 */
  public void connectTCP(String ipAddress, int port) {
  try {
 tcpCon = new TCPMasterConnection(InetAddress.getByName(ipAddress));
  } catch (UnknownHostException e1) {
 JOptionPane.showMessageDialog(null, "Įveskite IP adresą", "Invalid input", JOptionPane.WARNING_MESSAGE);
 }
 tcpCon.setPort(port);
 try {
 tcpCon.connect();
 } catch (Exception e) {
 JOptionPane.showMessageDialog(null, "Nepavyko prisijungti prie serverio. [TCP/IP]", "Connection error",
  JOptionPane.ERROR_MESSAGE);
 }
 
 transactionTCP = new ModbusTCPTransaction(tcpCon);
 
 }
/**  * Set parameters for serial com. *
 * @param portName the port name
 * @param baudRate the baud rate
 * @param dataBits the data bits
 * @param stopBits the stop bits
 * @param parity the parity
 * @param encoding the encoding
 * @param echo the echo
 */
  public void connectSerial(String portName, int baudRate, int dataBits, int stopBits, String parity, String encoding,
 boolean echo) {
  SerialParameters params = new SerialParameters();
  params.setPortName(portName);
  params.setDatabits(dataBits);
  params.setParity(parity);
 params.setStopbits(stopBits);
 params.setEncoding(encoding);
 params.setEcho(echo);
 params.setBaudRate(baudRate);
  serialCon = new SerialConnection(params);
  try {
 serialCon.open();
  } catch (Exception e) {
  JOptionPane.showMessageDialog(null, "Nepavyko prisijungti prie serverio. [Serial port]", "Connection error",
 JOptionPane.ERROR_MESSAGE);
 }
 transactionSerial = new ModbusSerialTransaction(serialCon);
 }
/** * Close TCP connection. */
  public void closeTCP() {
 tcpCon.close();
 }
/** * Close Serial connection. */
  public void closeSerial() {
 serialCon.close();
 }
/** * Check if TCP connected. *
 * @return boolean value
 */
  public boolean isConnectedTCP() {
 return tcpCon.isConnected();
 
 }
/** * Check if Serial connected. *
 * @return boolean value
 */
  public boolean isOpenSerial() {
 return serialCon.isOpen();
 }
/** * Writes single 16bit number to register (16 bit integer).
 *
  * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWrite the data to write
 */
  public void WriteSingle_16Bit(int unitID, int startAddress, int dataToWrite) {
 SimpleRegister reg = new SimpleRegister(dataToWrite);
  write_sreq.setReference(startAddress);
  write_sreq.setUnitID(unitID);
  write_sreq.setRegister(reg);
 try {
  transaction(transactionTCP, transactionSerial, write_sreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception write 16");
  } catch (ModbusSlaveException e) {
  System.out.println("Modbus Slave Exception write 16");
  } catch (ModbusException e) {
 System.out.println("Modbus Exception write 16");
 }
 }
  /**
 * Writes double 16bit number to register (32 bit integer).
  *
 * @param unitID the unit id
 * @param startAddress the start address
  * @param dataToWrite the data to write
  */
 public void WriteSingle_32Bit(int unitID, int startAddress, int dataToWrite) {
 int count = 2;
 int HIGH = dataToWrite >> 16;
 int LOW = dataToWrite & 0xFFFF;
 regH = new SimpleRegister(HIGH);
 regL = new SimpleRegister(LOW);
  registers = new Register[count];
 for (int i = 0, a = 1; i < registers.length; i += 2, a += 2) {
  registers[i] = regL;
  registers[a] = regH;
  }
  write_mreq.setReference(startAddress);
 write_mreq.setUnitID(unitID);
 write_mreq.setRegisters(registers);
 try {
  transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ModbusIOException e) {
  System.out.println("Modbus IO Exception write 32");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception write 32");
 } catch (ModbusException e) {
  System.out.println("Modbus Exception write 32");
 }
 }
/**
 * Writes double 16bit number to register (32bit float).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWriteF the data to write f
 */
public void WriteSingle_Float(int unitID, int startAddress, float dataToWriteF) {
 int count = 2;
  int number = Float.floatToIntBits(dataToWriteF);
 int HIGH = number >> 16;
 int LOW = number & 0xFFFF;
 regH = new SimpleRegister(HIGH);
 regL = new SimpleRegister(LOW);
 registers = new Register[count];
 for (int i = 1, a = 0; i < registers.length; i += 2, a += 2) {
 registers[i] = regL;
 registers[a] = regH;
 }
  write_mreq.setReference(startAddress);
  write_mreq.setUnitID(unitID);
  write_mreq.setRegisters(registers);
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception write float");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception write float");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception write float");
 }
 }
 /**
 * Writes multiple 16bit numbers to chosen registers (16bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWrite the data to write
 * @param count the count
 */
 public void WriteMultiple_16Bit(int unitID, int startAddress, int dataToWrite, int count) {
 register = new SimpleRegister(dataToWrite);
 registers = new Register[count];
  for (int i = 0; i < registers.length; i++) {
 registers[i] = register;
  }
  write_mreq.setReference(startAddress);
 write_mreq.setUnitID(unitID);
 write_mreq.setRegisters(registers);
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
  } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mwrite 16");
  } catch (ModbusSlaveException e) {
  System.out.println("Modbus Slave Exception mwrite 16");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mwrite 16");
 }
 }
 /**
 * Writes multiple double 16bit numbers to chosen registers (32bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWrite the data to write
 * @param count the count
 */
  public void WriteMultiple_32Bit(int unitID, int startAddress, int dataToWrite, int count) {
 int HIGH = dataToWrite >> 16;
 int LOW = dataToWrite & 0xFFFF;
 regH = new SimpleRegister(HIGH);
 regL = new SimpleRegister(LOW);
 registers = new Register[count * 2];
  for (int i = 0, a = 1; i < registers.length; i += 2, a += 2) {
 registers[i] = regL;
  registers[a] = regH;
 }
  write_mreq.setReference(startAddress);
 write_mreq.setUnitID(unitID);
 write_mreq.setRegisters(registers);
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
  } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mwrite 32");
  } catch (ModbusSlaveException e) {
  System.out.println("Modbus Slave Exception mwrite 32");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mwrite 32");
 }
 }
 /**
 * Writes multiple double 16bit numbers to chosen registers (32bit float).
  *
 * @param unitID the unit id
  * @param startAddress the start address
 * @param dataToWriteF the data to write f
 * @param count the count
 */
 public void WriteMultiple_Float(int unitID, int startAddress, float dataToWriteF, int count) {
 int number = Float.floatToIntBits(dataToWriteF);
 int HIGH = number >> 16;
 int LOW = number & 0xFFFF;
 regH = new SimpleRegister(HIGH);
 regL = new SimpleRegister(LOW);
 registers = new Register[count * 2];
 for (int i = 1, a = 0; i < registers.length; i += 2, a += 2) {
 registers[i] = regL;
 registers[a] = regH;
 }
 write_mreq.setReference(startAddress);
 write_mreq.setUnitID(unitID);
 write_mreq.setRegisters(registers);
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mwrite float");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mwrite float");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mwrite float");
 }
 }
/**
 * Reads multiple 16bit numbers from chosen registers (16bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param count the count
 * @return multiple registers
 */
public BackEnd ReadMultiple_16Bit(int unitID, int startAddress, int count) {
 this.int16Result = new int[count];
 this.string16Result = new String[count];
  read_mreq.setUnitID(unitID);
  read_mreq.setReference(startAddress);
 read_mreq.setWordCount(count);
 try {
 transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mread 16");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mread 16");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mread 16");
 }
 for (int n = 0; n < read_mres.getWordCount(); n++) {
 int16Result[n] = read_mres.getRegisterValue(n);
 string16Result[n] = String.valueOf(int16Result[n]);
 }
 return this;
 }
/**
 * Reads multiple double 16bit numbers from chosen registers (32bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param count the count
 * @return multiple registers
 */
public BackEnd ReadMultiple_32Bit(int unitID, int startAddress, int count) {
 this.int32Result = new int[count];
 this.string32Result = new String[count];
 int[] z = new int[count * 2];
 int[] y = new int[count * 2];
  int[] h = new int[count];
  int[] l = new int[count];
 read_mreq.setUnitID(unitID);
 read_mreq.setReference(startAddress);
 read_mreq.setWordCount(count * 2);
  try {
 transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mread 32");
  } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mread 32");
  } catch (ModbusException e) {
 System.out.println("Modbus Exception mread 32");
 }
 for (int n = 0, i = 1; n < read_mres.getWordCount(); n += 2, i += 2) {
 z[n] = read_mres.getRegisterValue(n);
 y[i] = (read_mres.getRegisterValue(i) << 16);
 }
 for (int a = 0, b = 0; a < l.length; a++, b += 2) {
  l[a] = z[b];
 }
 for (int a = 0, b = 1; a < h.length; a++, b += 2) {
 h[a] = y[b];
  }
  for (int n = 0; n < int32Result.length; n++) {
  int32Result[n] = h[n] | l[n];
 string32Result[n] = String.valueOf(int32Result[n]);
 }
 return this;
 }
 /**
 * Reads multiple double 16bit numbers from chosen registers (32 bit float).
  *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param count the count
  * @return multiple registers
 */
 public BackEnd ReadMultiple_Float(int unitID, int startAddress, int count) {
  this.floatResult = new float[count];
 this.stringFloatResult = new String[count];
 this.roundFloatResult = new float[count];
 this.roundStringFloatResult = new String[count];
 int[] x = new int[count * 2];
 int[] y = new int[count * 2];
 int[] h = new int[count];
 int[] l = new int[count];
 read_mreq.setUnitID(unitID);
  read_mreq.setReference(startAddress);
 read_mreq.setWordCount(count * 2);
 try {
  transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mread float");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mread float");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mread float");
 }
  for (int n = 1, i = 0; n < read_mres.getWordCount(); n += 2, i += 2) {
  x[n] = read_mres.getRegisterValue(n);
  y[i] = (read_mres.getRegisterValue(i) << 16);
 }
 for (int a = 0, b = 1; a < l.length; a++, b += 2) {
 l[a] = x[b];
 }
 for (int a = 0, b = 0; a < h.length; a++, b += 2) {
 h[a] = y[b];
 }
 for (int n = 0; n < floatResult.length; n++) {
  floatResult[n] = Float.intBitsToFloat(h[n] | l[n]);
  stringFloatResult[n] = String.valueOf(floatResult[n]);
  roundFloatResult[n] = (float) Math.round(floatResult[n] * 100) / 100;
 roundStringFloatResult[n] = Float.toString(roundFloatResult[n]);
 }
 return this;
 }
 /**
 * Reads multiple coils from chosen registers.  *
 * @param unitID the unit id
  * @param startAddress the start address
 * @param count the count
 * @return coil as boolean or String
  */
 public BackEnd ReadCoilStatus(int unitID, int startAddress, int count) {
  this.booleanCoilResult = new boolean[count];
 this.stringCoilResult = new String[count];
 rcreq.setReference(startAddress);
 rcreq.setBitCount(count);
 rcreq.setUnitID(unitID);
  try {
  transaction(transactionTCP, transactionSerial, rcreq);
 } catch (ModbusIOException e) {
 e.printStackTrace();
  } catch (ModbusSlaveException e) {
  e.printStackTrace();
  } catch (ModbusException e) {
  e.printStackTrace();
  }
  for (int i = 0; i < count; i++) {
 booleanCoilResult[i] = rcres.getCoilStatus(i);
  stringCoilResult[i] = String.valueOf(booleanCoilResult[i]);
 }
 return this;
 }
 /**
 * Reads multiple discrete inputs from chosen registers.
 *
 * @param unitID the unit id
  * @param startAddress the start address
  * @param count the count
  * @return discrete input as boolean or String
 */
 public BackEnd ReadDiscreteInputStatus(int unitID, int startAddress, int count) {
 this.booleanDiscreteInputResult = new boolean[count];
 this.stringDiscreteInputResult = new String[count];
 ridreq.setReference(startAddress);
 ridreq.setBitCount(count);
 ridreq.setUnitID(unitID);
 try {
 transaction(transactionTCP, transactionSerial, ridreq);
  } catch (ModbusIOException e) {
 e.printStackTrace();
  } catch (ModbusSlaveException e) {
  e.printStackTrace();
 } catch (ModbusException e) {
 e.printStackTrace();
  }
 for (int i = 0; i < count; i++) {
  booleanDiscreteInputResult[i] = ridres.getDiscreteStatus(i);
 stringDiscreteInputResult[i] = String.valueOf(booleanDiscreteInputResult[i]);
 }
 return this;
 }
 /**
  * Reads multiple analog inputs from chosen registers.
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param count the count
 * @return analog input register value (int or String)
 */
 public BackEnd ReadAnalogInputRegisters(int unitID, int startAddress, int count) {
 this.intAnalogInputRegistersResult = new int[count];
 this.stringAnalogInputRegistersResult = new String[count];
  rireq.setReference(startAddress);
  rireq.setWordCount(count);
  rireq.setUnitID(unitID);
  try {
 transaction(transactionTCP, transactionSerial, rireq);
 } catch (ModbusIOException e) {
 e.printStackTrace();
  } catch (ModbusSlaveException e) {
 e.printStackTrace();
  } catch (ModbusException e) {
 e.printStackTrace();
 }
 for (int i = 0; i < count; i++) {
 intAnalogInputRegistersResult[i] = rires.getRegisterValue(i);
 stringAnalogInputRegistersResult[i] = String.valueOf(intAnalogInputRegistersResult[i]);
 }
 return this;
 }
 /**
 * Read bit from a register.
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param position  D15..D0
 * @param count the count
 * @return bit as boolean or String
 */
public BackEnd ReadBit(int unitID, int startAddress, int position, int count) {
 this.stringReadBitResult = new String[count];
  this.booleanReadBitResult = new boolean[count];
 this.toString = new String[count];
 // String[] toString = new String[count];
 read_mreq.setUnitID(unitID);
 read_mreq.setReference(startAddress);
 read_mreq.setWordCount(count);
  try {
  transaction(transactionTCP, transactionSerial, read_mreq);
  } catch (ModbusIOException e) {
  System.out.println("Modbus IO Exception read bit");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception read bit");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception read bit");
 }
  for (int n = 0; n < read_mres.getWordCount(); n++) {
 try {
 toString[n] = Integer.toBinaryString(0x10000 | read_mres.getRegisterValue(n)).substring(1);
  if (toString[n].charAt(15 - position) == '0') {
 booleanReadBitResult[n] = false;
  stringReadBitResult[n] = String.valueOf(false);
  } else if (toString[n].charAt(15 - position) == '1') {
  booleanReadBitResult[n] = true;
  stringReadBitResult[n] = String.valueOf(true);
 }
 } catch (IndexOutOfBoundsException e) {
  }
  }
 return this;
 }
 /**
 * Write bit to a register.
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param position D15..D0
  * @param bitas true=0, false=1
 * @param count the count
 */
 public void WriteBit(int unitID, int startAddress, int position, boolean bitas, int count) {
  String value = "";
 if (bitas == true) {
 value = "1";
 } else if (bitas == false) {
 value = "0";
  }
 int[] x = new int[count];
 String[] toString = new String[count];
  String[] Format16Bit = new String[count];
 read_mreq.setUnitID(unitID);
  read_mreq.setReference(startAddress);
 read_mreq.setWordCount(count);
 try {
 transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception Readwrite bit");
  } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception Readwrite bit");
  } catch (ModbusException e) {
 System.out.println("Modbus Exception Readwrite bit");
 }
 for (int n = 0; n < read_mres.getWordCount(); n++) {
 toString[n] = Integer.toBinaryString(0x10000 | read_mres.getRegisterValue(n)).substring(1);
 }
 registers = new Register[count];
 for (int n = 0; n < count; n++) {
 Format16Bit[n] = toString[n].substring(0, 15 - position) + value + toString[n].substring(15 - position + 1);
 x[n] = Integer.parseInt(Format16Bit[n], 2);
 register = new SimpleRegister(x[n]);
 registers[n] = register;
 }
 write_mreq.setReference(startAddress);
 write_mreq.setRegisters(registers);
 write_mreq.setUnitID(unitID);
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception Write bit");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception Write bit");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception Write bit");
 }
 }
 /**
  * Overloading method for transaction over modbus protocol.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param write_mreq the write_mreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
 public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 WriteMultipleRegistersRequest write_mreq) throws ModbusIOException, ModbusSlaveException, ModbusException {
  try {
 transactionTCP.setRequest(write_mreq);
 transactionTCP.execute();
 transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] write_mreq error");
 }
 try {
  transactionSerial.setRequest(write_mreq);
 transactionSerial.execute();
  transactionSerial.getResponse();
  } catch (Exception e) {
  System.out.println("[Serial] write_mreq error");
 }

 }
 /**
  * Overloading method.
 *
  * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param write_sreq the write_sreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
 public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
  WriteSingleRegisterRequest write_sreq) throws ModbusIOException, ModbusSlaveException, ModbusException {
 try {
 transactionTCP.setRequest(write_sreq);
 transactionTCP.execute();
 transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] write_sreq error");
 }
 try {
  transactionSerial.setRequest(write_sreq); transactionSerial.execute();
  transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] write_sreq error");
 }
 }
 /**
  * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param read_mreq the read_mreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
 public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 ReadMultipleRegistersRequest read_mreq) throws ModbusIOException, ModbusSlaveException, ModbusException {
  try {
 transactionTCP.setRequest(read_mreq);
  transactionTCP.execute();
  read_mres = (ReadMultipleRegistersResponse) transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] read_mreq error");
 }
 try {
 
  transactionSerial.setRequest(read_mreq);
 transactionSerial.execute();
 read_mres = (ReadMultipleRegistersResponse) transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] read_mreq error");
 }
 }
/**
 * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param rcreq the rcreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
  ReadCoilsRequest rcreq) throws ModbusIOException, ModbusSlaveException, ModbusException {
 try {
 transactionTCP.setRequest(rcreq);
 transactionTCP.execute();
 rcres = (ReadCoilsResponse) transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] rcreq error");
 }
 try {
 transactionSerial.setRequest(rcreq);
 transactionSerial.execute();
 rcres = (ReadCoilsResponse) transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] rcreq error");
 }
 }
 /**
 * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param rireq the rireq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
 public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 ReadInputRegistersRequest rireq) throws ModbusIOException, ModbusSlaveException, ModbusException {
  try {
  transactionTCP.setRequest(rireq);
  transactionTCP.execute();
  rires = (ReadInputRegistersResponse) transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] rireq error");
 }
 try {
  transactionSerial.setRequest(rireq);
  transactionSerial.execute();
  rires = (ReadInputRegistersResponse) transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] rireq error");
 }
 }
 /**
 * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param ridreq the ridreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
  * @throws ModbusException the modbus exception
 */
 public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 ReadInputDiscretesRequest ridreq) throws ModbusIOException, ModbusSlaveException, ModbusException {
  try {
  transactionTCP.setRequest(ridreq);
  transactionTCP.execute();
  ridres = (ReadInputDiscretesResponse) transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] ridreq error");
 }
 try {
  transactionSerial.setRequest(ridreq);
  transactionSerial.execute();
 ridres = (ReadInputDiscretesResponse) transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] ridreq error");
 }
 }
 /**
 * Gets the 16 bit int.
 *
 * @return 16bit numbers as int array
  */
 public int[] get16BitInt() {
 return int16Result;
 }
 /**
 * Gets the 32 bit int.
 *
 * @return 32bit numbers as int array
 */
 public int[] get32BitInt() {
 return int32Result;
 }
 /**
 * Gets the float.
 *
 * @return 32bit float numbers as float array
  */
 public float[] getFloat() {
 return floatResult;
 }
 /**
 * Gets the round float.
 *
 * @return 32bit float numbers as rounded float array
  */
 public float[] getRoundFloat() {
 return roundFloatResult;
 }
 /**
 * Gets the 16 bit string.
 *
 * @return 16bit numbers as String array
  */
 public String[] get16BitString() {
 return string16Result;
 }
 /**
 * Gets the 32 bit string.
 *
 * @return 32bit numbers as String array
 */
 public String[] get32BitString() {
 return string32Result;
 }
 /**
 * Gets the float string.
 *
 * @return 32bit float numbers as String array
 */
 public String[] getFloatString() {
 return stringFloatResult;
 }
/**
 * Gets the round float string.
 *
 * @return 32bit float numbers as rounded String array
 */
public String[] getRoundFloatString() {
 return roundStringFloatResult;
}
/**
 * Gets the 16 bit at index.
 *
 * @param index the index
 * @return 16bit number from int array at index
 */
public int get16BitAtIndex(int index) {
 return int16Result[index];
}
/**
 * Gets the 32 bit at index.
 *
 * @param index the index
 * @return 32bit number from int array at index
 */
public int get32BitAtIndex(int index) {
 return int32Result[index];
}
/**
 * Gets the float at index.
 *
 * @param index the index
 * @return 32bit foat number from float array at index
 */
public float getFloatAtIndex(int index) {
 return floatResult[index];
}
/**
 * Gets the round float at index.
 *
 * @param index the index
 * @return 32bit rounded float number from rounded float array at index
 */
public float getRoundFloatAtIndex(int index) {
 return roundFloatResult[index];
}
/**
 * Gets the 16 bit string at index.
 *
 * @param index the index
 * @return 16bit rounded float number from rounded String array at index
 */
public String get16BitStringAtIndex(int index) {
 return string16Result[index];
}
/**
 * Gets the 32 bit string at index.
 *
 * @param index the index
 * @return 32bit number from String array at index
 */
public String get32BitStringAtIndex(int index) {
 return string32Result[index];
}
/**
 * Gets the float string at index.
 *
 * @param index the index
 * @return 32bit float number from String array at index
 */
public String getFloatStringAtIndex(int index) {
 return stringFloatResult[index];
}
/**
 * Gets the round float string at index.
 *
 * @param index the index
 * @return 32bit rounded float number from rounded String array at index
 */
public String getRoundFloatStringAtIndex(int index) {
 return roundStringFloatResult[index];
}
/**
 * Gets the coil boolean at index.
 *
 * @param index the index
 * @return coil status from boolean array at index
 */
public Boolean getCoilBooleanAtIndex(int index) {
 return booleanCoilResult[index];
}
/**
 * Gets the coil string at index.
 *
 * @param index the index
 * @return coil status from String array at index
 */
public String getCoilStringAtIndex(int index) {
 return stringCoilResult[index];
}
/**
 * Gets the coil boolean.
 *
 * @return coil status from boolean array
 */
public boolean[] getCoilBoolean() {
 return booleanCoilResult;
}
/**
 * Gets the coil string.
 *
 * @return coil status from String array
 */
public String[] getCoilString() {
 return stringCoilResult;
}
/**
 * Gets the read bit boolean.
 *
 * @return bit status from boolean array
 */
public boolean[] getReadBitBoolean() {
 return booleanReadBitResult;
}
/**
 * Gets the read bit boolean at index.
 *
 * @param index the index
 * @return bit status from boolean array at index
 */
public boolean getReadBitBooleanAtIndex(int index) {
 return booleanReadBitResult[index];
}
/**
 * Gets the read bit string.
 *
 * @return bit status from String array
 */
public String[] getReadBitString() {
 return stringReadBitResult;
}
/**
 * Gets the read bit string bin.
 *
 * @return String binary format (01010101..)
 */
public String[] getReadBitStringBin() {
 StringBuilder[] str = new StringBuilder[toString.length];
 for (int i = 0; i < str.length; i++) {
 str[i] = new StringBuilder(toString[i]);
 int idx = str[i].length() - 4;
 while (idx > 0) {
 str[i].insert(idx, " ");
 toString[i] = str[i].toString();
 idx = idx - 4;
 }
 }
 return toString;
 }
/**
 * Gets the read bit string at index.
 *
 * @param index the index
 * @return bit status from String array at index
 */
public String getReadBitStringAtIndex(int index) {
 return stringReadBitResult[index];
}
/**
 * Gets the boolean discrete input result.
 *
 * @return dicrete input status from boolean array
 */
public boolean[] getBooleanDiscreteInputResult() {
 return booleanDiscreteInputResult;
}
/**
 * Gets the boolean discrete input result at index.
 *
 * @param index the index
 * @return dicrete input status from boolean array at index
 */
public boolean getBooleanDiscreteInputResultAtIndex(int index) {
 return booleanDiscreteInputResult[index];
}
/**
 * Gets the string discrete input result.
 *
 * @return dicrete input status from String array
 */
public String[] getStringDiscreteInputResult() {
 return stringDiscreteInputResult;
}
/**
 * Gets the string discrete input result at index.
 *
 * @param index the index
 * @return dicrete input status from String array at index
 */
public String getStringDiscreteInputResultAtIndex(int index) {
 return stringDiscreteInputResult[index];
}
/**
 * Gets the int analog input registers result.
 *
 * @return analog input status from int array
 */
public int[] getIntAnalogInputRegistersResult() {
 return intAnalogInputRegistersResult;
}
/**
 * Gets the int analog input registers result at index.
 *
 * @param index the index
 * @return analog input status from int array at index
 */
public int getIntAnalogInputRegistersResultAtIndex(int index) {
 return intAnalogInputRegistersResult[index];
}
/**
 * Gets the string analog input registers result.
 *
 * @return analog input status from String array
 */
public String[] getStringAnalogInputRegistersResult() {
 return stringAnalogInputRegistersResult;
}
/**
 * Gets the string analog input registers result at index.
 *
 * @param index the index
 * @return analog input status from String array at index
 */
public String getStringAnalogInputRegistersResultAtIndex(int index) {
 return stringAnalogInputRegistersResult[index];
 }
}
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Bumped by Community user
Source Link

Modbus connection over TCP and Serial port

I want to improve my code. In this code I don't like my contructor, but without it I keep getting an error while trying to connect NullPointerException.Any suggestions are welcome.

package soft;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.JOptionPane;
import net.wimpi.modbus.ModbusException;
import net.wimpi.modbus.ModbusIOException;
import net.wimpi.modbus.ModbusSlaveException;
import net.wimpi.modbus.io.ModbusSerialTransaction;
import net.wimpi.modbus.io.ModbusTCPTransaction;
import net.wimpi.modbus.msg.ReadCoilsRequest;
import net.wimpi.modbus.msg.ReadCoilsResponse;
import net.wimpi.modbus.msg.ReadInputDiscretesRequest;
import net.wimpi.modbus.msg.ReadInputDiscretesResponse;
import net.wimpi.modbus.msg.ReadInputRegistersRequest;
import net.wimpi.modbus.msg.ReadInputRegistersResponse;
import net.wimpi.modbus.msg.ReadMultipleRegistersRequest;
import net.wimpi.modbus.msg.ReadMultipleRegistersResponse;
import net.wimpi.modbus.msg.WriteMultipleRegistersRequest;
import net.wimpi.modbus.msg.WriteMultipleRegistersResponse;
import net.wimpi.modbus.msg.WriteSingleRegisterRequest;
import net.wimpi.modbus.msg.WriteSingleRegisterResponse;
import net.wimpi.modbus.net.SerialConnection;
import net.wimpi.modbus.net.TCPMasterConnection;
import net.wimpi.modbus.procimg.Register;
import net.wimpi.modbus.procimg.SimpleRegister;
import net.wimpi.modbus.util.SerialParameters;
/**
 * This class realizes modbus protocol
 * communication over TCP and Serial Port and most of modbus functions.
 *
 * @author Tomas Ausvicas
 */
public class BackEnd {
/** The tcp con. */
TCPMasterConnection tcpCon;
/** The serial con. */
SerialConnection serialCon;
/** The transaction tcp. */
ModbusTCPTransaction transactionTCP;
/** The transaction serial. */
ModbusSerialTransaction transactionSerial;
/** The params. */
SerialParameters params = new SerialParameters();
/** The rcreq. */
ReadCoilsRequest rcreq = new ReadCoilsRequest();
/** The rcres. */
ReadCoilsResponse rcres = new ReadCoilsResponse();
/** The rireq. */
ReadInputRegistersRequest rireq = new ReadInputRegistersRequest();
/** The rires. */
ReadInputRegistersResponse rires = new ReadInputRegistersResponse();
/** The ridreq. */
ReadInputDiscretesRequest ridreq = new ReadInputDiscretesRequest();
/** The ridres. */
ReadInputDiscretesResponse ridres = new ReadInputDiscretesResponse();
/** The write_sreq. */
WriteSingleRegisterRequest write_sreq = new WriteSingleRegisterRequest();
/** The write_sres. */
WriteSingleRegisterResponse write_sres = new WriteSingleRegisterResponse();
/** The read_mreq. */
ReadMultipleRegistersRequest read_mreq = new ReadMultipleRegistersRequest();
/** The read_mres. */
ReadMultipleRegistersResponse read_mres = new `ReadMultipleRegistersResponse();`
/** The write_mreq. */
WriteMultipleRegistersRequest write_mreq = new WriteMultipleRegistersRequest();
/** The write_mres. */
WriteMultipleRegistersResponse write_mres = new WriteMultipleRegistersResponse();
/** The register. */
SimpleRegister regL, regH, register;
/** The registers. */
Register[] registers;
/** The int16 result. */
private int[] int16Result;
/** The int32 result. */
private int[] int32Result;
/** The float result. */
private float[] floatResult;
/** The round float result. */
private float[] roundFloatResult;
/** The string16 result. */
private String[] string16Result;
/** The string32 result. */
private String[] string32Result;
/** The string float result. */
private String[] stringFloatResult;
/** The round string float result. */
private String[] roundStringFloatResult;
/** The string coil result. */
private String[] stringCoilResult;
/** The boolean coil result. */
private boolean[] booleanCoilResult;
/** The string discrete input result. */
private String[] stringDiscreteInputResult;
/** The boolean discrete input result. */
private boolean[] booleanDiscreteInputResult;
/** The string read bit result. */
private String[] stringReadBitResult;
/** The boolean read bit result. */
private boolean[] booleanReadBitResult;
/** The int analog input registers result. */
private int[] intAnalogInputRegistersResult;
/** The string analog input registers result. */
private String[] stringAnalogInputRegistersResult;
/** The to string. */
private String[] toString;
/**
 * Default constructor with TCP and Serial Port objects created.
 */
public BackEnd() {
try {
 tcpCon = new TCPMasterConnection(InetAddress.getByName(""));
} catch (UnknownHostException e) {
 System.out.println("Unknow Host");
}
params = new SerialParameters();
serialCon = new SerialConnection(params);
}
/**
 * Connect over TCP.
 *
 * @param ipAddress the ip address
 * @param port the port
 */
public void connectTCP(String ipAddress, int port) {
 try {
 tcpCon = new TCPMasterConnection(InetAddress.getByName(ipAddress));
 } catch (UnknownHostException e1) {
 JOptionPane.showMessageDialog(null, "Įveskite IP adresą", "Invalid input", JOptionPane.WARNING_MESSAGE);
 }
 tcpCon.setPort(port);
 try {
 tcpCon.connect();
 } catch (Exception e) {
 JOptionPane.showMessageDialog(null, "Nepavyko prisijungti prie serverio. [TCP/IP]", "Connection error",
 JOptionPane.ERROR_MESSAGE);
 }
 
 transactionTCP = new ModbusTCPTransaction(tcpCon);
 
}
/**
 * Set parameters for serial com.
 *
 * @param portName the port name
 * @param baudRate the baud rate
 * @param dataBits the data bits
 * @param stopBits the stop bits
 * @param parity the parity
 * @param encoding the encoding
 * @param echo the echo
 */
public void connectSerial(String portName, int baudRate, int dataBits, int stopBits, String parity, String encoding,
 boolean echo) {
 SerialParameters params = new SerialParameters();
 params.setPortName(portName);
 params.setDatabits(dataBits);
 params.setParity(parity);
 params.setStopbits(stopBits);
 params.setEncoding(encoding);
 params.setEcho(echo);
 params.setBaudRate(baudRate);
 serialCon = new SerialConnection(params);
 try {
 serialCon.open();
 } catch (Exception e) {
 JOptionPane.showMessageDialog(null, "Nepavyko prisijungti prie serverio. [Serial port]", "Connection error",
 JOptionPane.ERROR_MESSAGE);
 }
 transactionSerial = new ModbusSerialTransaction(serialCon);
}
/**
 * Close TCP connection.
 */
public void closeTCP() {
 tcpCon.close();
}
/**
 * Close Serial connection.
 */
public void closeSerial() {
 serialCon.close();
}
/**
 * Check if TCP connected.
 *
 * @return boolean value
 */
public boolean isConnectedTCP() {
 return tcpCon.isConnected();
 
}
/**
 * Check if Serial connected.
 *
 * @return boolean value
 */
public boolean isOpenSerial() {
 return serialCon.isOpen();
}
/**
 * Writes single 16bit number to register (16 bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWrite the data to write
 */
public void WriteSingle_16Bit(int unitID, int startAddress, int dataToWrite) {
 SimpleRegister reg = new SimpleRegister(dataToWrite);
 write_sreq.setReference(startAddress);
 write_sreq.setUnitID(unitID);
 write_sreq.setRegister(reg);
 try {
 transaction(transactionTCP, transactionSerial, write_sreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception write 16");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception write 16");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception write 16");
 }
}
/**
 * Writes double 16bit number to register (32 bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWrite the data to write
 */
public void WriteSingle_32Bit(int unitID, int startAddress, int dataToWrite) {
 int count = 2;
 int HIGH = dataToWrite >> 16;
 int LOW = dataToWrite & 0xFFFF;
 regH = new SimpleRegister(HIGH);
 regL = new SimpleRegister(LOW);
 registers = new Register[count];
 for (int i = 0, a = 1; i < registers.length; i += 2, a += 2) {
 registers[i] = regL;
 registers[a] = regH;
 }
 write_mreq.setReference(startAddress);
 write_mreq.setUnitID(unitID);
 write_mreq.setRegisters(registers);
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception write 32");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception write 32");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception write 32");
 }
}
/**
 * Writes double 16bit number to register (32bit float).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWriteF the data to write f
 */
public void WriteSingle_Float(int unitID, int startAddress, float dataToWriteF) {
 int count = 2;
 int number = Float.floatToIntBits(dataToWriteF);
 int HIGH = number >> 16;
 int LOW = number & 0xFFFF;
 regH = new SimpleRegister(HIGH);
 regL = new SimpleRegister(LOW);
 registers = new Register[count];
 for (int i = 1, a = 0; i < registers.length; i += 2, a += 2) {
 registers[i] = regL;
 registers[a] = regH;
 }
 write_mreq.setReference(startAddress);
 write_mreq.setUnitID(unitID);
 write_mreq.setRegisters(registers);
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception write float");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception write float");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception write float");
 }
}
/**
 * Writes multiple 16bit numbers to chosen registers (16bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWrite the data to write
 * @param count the count
 */
public void WriteMultiple_16Bit(int unitID, int startAddress, int dataToWrite, int count) {
 register = new SimpleRegister(dataToWrite);
 registers = new Register[count];
 for (int i = 0; i < registers.length; i++) {
 registers[i] = register;
 }
 write_mreq.setReference(startAddress);
 write_mreq.setUnitID(unitID);
 write_mreq.setRegisters(registers);
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mwrite 16");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mwrite 16");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mwrite 16");
 }
}
/**
 * Writes multiple double 16bit numbers to chosen registers (32bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWrite the data to write
 * @param count the count
 */
public void WriteMultiple_32Bit(int unitID, int startAddress, int dataToWrite, int count) {
 int HIGH = dataToWrite >> 16;
 int LOW = dataToWrite & 0xFFFF;
 regH = new SimpleRegister(HIGH);
 regL = new SimpleRegister(LOW);
 registers = new Register[count * 2];
 for (int i = 0, a = 1; i < registers.length; i += 2, a += 2) {
 registers[i] = regL;
 registers[a] = regH;
 }
 write_mreq.setReference(startAddress);
 write_mreq.setUnitID(unitID);
 write_mreq.setRegisters(registers);
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mwrite 32");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mwrite 32");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mwrite 32");
 }
}
/**
 * Writes multiple double 16bit numbers to chosen registers (32bit float).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param dataToWriteF the data to write f
 * @param count the count
 */
public void WriteMultiple_Float(int unitID, int startAddress, float dataToWriteF, int count) {
 int number = Float.floatToIntBits(dataToWriteF);
 int HIGH = number >> 16;
 int LOW = number & 0xFFFF;
 regH = new SimpleRegister(HIGH);
 regL = new SimpleRegister(LOW);
 registers = new Register[count * 2];
 for (int i = 1, a = 0; i < registers.length; i += 2, a += 2) {
 registers[i] = regL;
 registers[a] = regH;
 }
 write_mreq.setReference(startAddress);
 write_mreq.setUnitID(unitID);
 write_mreq.setRegisters(registers);
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mwrite float");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mwrite float");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mwrite float");
 }
}
/**
 * Reads multiple 16bit numbers from chosen registers (16bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param count the count
 * @return multiple registers
 */
public BackEnd ReadMultiple_16Bit(int unitID, int startAddress, int count) {
 this.int16Result = new int[count];
 this.string16Result = new String[count];
 read_mreq.setUnitID(unitID);
 read_mreq.setReference(startAddress);
 read_mreq.setWordCount(count);
 try {
 transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mread 16");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mread 16");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mread 16");
 }
 for (int n = 0; n < read_mres.getWordCount(); n++) {
 int16Result[n] = read_mres.getRegisterValue(n);
 string16Result[n] = String.valueOf(int16Result[n]);
 }
 return this;
}
/**
 * Reads multiple double 16bit numbers from chosen registers (32bit integer).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param count the count
 * @return multiple registers
 */
public BackEnd ReadMultiple_32Bit(int unitID, int startAddress, int count) {
 this.int32Result = new int[count];
 this.string32Result = new String[count];
 int[] z = new int[count * 2];
 int[] y = new int[count * 2];
 int[] h = new int[count];
 int[] l = new int[count];
 read_mreq.setUnitID(unitID);
 read_mreq.setReference(startAddress);
 read_mreq.setWordCount(count * 2);
 try {
 transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mread 32");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mread 32");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mread 32");
 }
 for (int n = 0, i = 1; n < read_mres.getWordCount(); n += 2, i += 2) {
 z[n] = read_mres.getRegisterValue(n);
 y[i] = (read_mres.getRegisterValue(i) << 16);
 }
 for (int a = 0, b = 0; a < l.length; a++, b += 2) {
 l[a] = z[b];
 }
 for (int a = 0, b = 1; a < h.length; a++, b += 2) {
 h[a] = y[b];
 }
 for (int n = 0; n < int32Result.length; n++) {
 int32Result[n] = h[n] | l[n];
 string32Result[n] = String.valueOf(int32Result[n]);
 }
 return this;
}
/**
 * Reads multiple double 16bit numbers from chosen registers (32 bit float).
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param count the count
 * @return multiple registers
 */
public BackEnd ReadMultiple_Float(int unitID, int startAddress, int count) {
 this.floatResult = new float[count];
 this.stringFloatResult = new String[count];
 this.roundFloatResult = new float[count];
 this.roundStringFloatResult = new String[count];
 int[] x = new int[count * 2];
 int[] y = new int[count * 2];
 int[] h = new int[count];
 int[] l = new int[count];
 read_mreq.setUnitID(unitID);
 read_mreq.setReference(startAddress);
 read_mreq.setWordCount(count * 2);
 try {
 transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception mread float");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception mread float");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception mread float");
 }
 for (int n = 1, i = 0; n < read_mres.getWordCount(); n += 2, i += 2) {
 x[n] = read_mres.getRegisterValue(n);
 y[i] = (read_mres.getRegisterValue(i) << 16);
 }
 for (int a = 0, b = 1; a < l.length; a++, b += 2) {
 l[a] = x[b];
 }
 for (int a = 0, b = 0; a < h.length; a++, b += 2) {
 h[a] = y[b];
 }
 for (int n = 0; n < floatResult.length; n++) {
 floatResult[n] = Float.intBitsToFloat(h[n] | l[n]);
 stringFloatResult[n] = String.valueOf(floatResult[n]);
 roundFloatResult[n] = (float) Math.round(floatResult[n] * 100) / 100;
 roundStringFloatResult[n] = Float.toString(roundFloatResult[n]);
 }
 return this;
}
/**
 * Reads multiple coils from chosen registers.
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param count the count
 * @return coil as boolean or String
 */
public BackEnd ReadCoilStatus(int unitID, int startAddress, int count) {
 this.booleanCoilResult = new boolean[count];
 this.stringCoilResult = new String[count];
 rcreq.setReference(startAddress);
 rcreq.setBitCount(count);
 rcreq.setUnitID(unitID);
 try {
 transaction(transactionTCP, transactionSerial, rcreq);
 } catch (ModbusIOException e) {
 e.printStackTrace();
 } catch (ModbusSlaveException e) {
 e.printStackTrace();
 } catch (ModbusException e) {
 e.printStackTrace();
 }
 for (int i = 0; i < count; i++) {
 booleanCoilResult[i] = rcres.getCoilStatus(i);
 stringCoilResult[i] = String.valueOf(booleanCoilResult[i]);
 }
 return this;
}
/**
 * Reads multiple discrete inputs from chosen registers.
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param count the count
 * @return discrete input as boolean or String
 */
public BackEnd ReadDiscreteInputStatus(int unitID, int startAddress, int count) {
 this.booleanDiscreteInputResult = new boolean[count];
 this.stringDiscreteInputResult = new String[count];
 ridreq.setReference(startAddress);
 ridreq.setBitCount(count);
 ridreq.setUnitID(unitID);
 try {
 transaction(transactionTCP, transactionSerial, ridreq);
 } catch (ModbusIOException e) {
 e.printStackTrace();
 } catch (ModbusSlaveException e) {
 e.printStackTrace();
 } catch (ModbusException e) {
 e.printStackTrace();
 }
 for (int i = 0; i < count; i++) {
 booleanDiscreteInputResult[i] = ridres.getDiscreteStatus(i);
 stringDiscreteInputResult[i] = String.valueOf(booleanDiscreteInputResult[i]);
 }
 return this;
}
/**
 * Reads multiple analog inputs from chosen registers.
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param count the count
 * @return analog input register value (int or String)
 */
public BackEnd ReadAnalogInputRegisters(int unitID, int startAddress, int count) {
 this.intAnalogInputRegistersResult = new int[count];
 this.stringAnalogInputRegistersResult = new String[count];
 rireq.setReference(startAddress);
 rireq.setWordCount(count);
 rireq.setUnitID(unitID);
 try {
 transaction(transactionTCP, transactionSerial, rireq);
 } catch (ModbusIOException e) {
 e.printStackTrace();
 } catch (ModbusSlaveException e) {
 e.printStackTrace();
 } catch (ModbusException e) {
 e.printStackTrace();
 }
 for (int i = 0; i < count; i++) {
 intAnalogInputRegistersResult[i] = rires.getRegisterValue(i);
 stringAnalogInputRegistersResult[i] = String.valueOf(intAnalogInputRegistersResult[i]);
 }
 return this;
}
/**
 * Read bit from a register.
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param position D15..D0
 * @param count the count
 * @return bit as boolean or String
 */
public BackEnd ReadBit(int unitID, int startAddress, int position, int count) {
 this.stringReadBitResult = new String[count];
 this.booleanReadBitResult = new boolean[count];
 this.toString = new String[count];
 // String[] toString = new String[count];
 read_mreq.setUnitID(unitID);
 read_mreq.setReference(startAddress);
 read_mreq.setWordCount(count);
 try {
 transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception read bit");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception read bit");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception read bit");
 }
 for (int n = 0; n < read_mres.getWordCount(); n++) {
 try {
 toString[n] = Integer.toBinaryString(0x10000 | read_mres.getRegisterValue(n)).substring(1);
 if (toString[n].charAt(15 - position) == '0') {
 booleanReadBitResult[n] = false;
 stringReadBitResult[n] = String.valueOf(false);
 } else if (toString[n].charAt(15 - position) == '1') {
 booleanReadBitResult[n] = true;
 stringReadBitResult[n] = String.valueOf(true);
 }
 } catch (IndexOutOfBoundsException e) {
 }
 }
 return this;
}
/**
 * Write bit to a register.
 *
 * @param unitID the unit id
 * @param startAddress the start address
 * @param position D15..D0
 * @param bitas true=0, false=1
 * @param count the count
 */
public void WriteBit(int unitID, int startAddress, int position, boolean bitas, int count) {
 String value = "";
 if (bitas == true) {
 value = "1";
 } else if (bitas == false) {
 value = "0";
 }
 int[] x = new int[count];
 String[] toString = new String[count];
 String[] Format16Bit = new String[count];
 read_mreq.setUnitID(unitID);
 read_mreq.setReference(startAddress);
 read_mreq.setWordCount(count);
 try {
 transaction(transactionTCP, transactionSerial, read_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception Readwrite bit");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception Readwrite bit");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception Readwrite bit");
 }
 for (int n = 0; n < read_mres.getWordCount(); n++) {
 toString[n] = Integer.toBinaryString(0x10000 | read_mres.getRegisterValue(n)).substring(1);
 }
 registers = new Register[count];
 for (int n = 0; n < count; n++) {
 Format16Bit[n] = toString[n].substring(0, 15 - position) + value + toString[n].substring(15 - position + 1);
 x[n] = Integer.parseInt(Format16Bit[n], 2);
 register = new SimpleRegister(x[n]);
 registers[n] = register;
 }
 write_mreq.setReference(startAddress);
 write_mreq.setRegisters(registers);
 write_mreq.setUnitID(unitID);
 try {
 transaction(transactionTCP, transactionSerial, write_mreq);
 } catch (ModbusIOException e) {
 System.out.println("Modbus IO Exception Write bit");
 } catch (ModbusSlaveException e) {
 System.out.println("Modbus Slave Exception Write bit");
 } catch (ModbusException e) {
 System.out.println("Modbus Exception Write bit");
 }
}
/**
 * Overloading method for transaction over modbus protocol.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param write_mreq the write_mreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 WriteMultipleRegistersRequest write_mreq) throws ModbusIOException, ModbusSlaveException, ModbusException {
 try {
 transactionTCP.setRequest(write_mreq);
 transactionTCP.execute();
 transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] write_mreq error");
 }
 try {
 transactionSerial.setRequest(write_mreq);
 transactionSerial.execute();
 transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] write_mreq error");
 }
}
/**
 * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param write_sreq the write_sreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 WriteSingleRegisterRequest write_sreq) throws ModbusIOException, ModbusSlaveException, ModbusException {
 try {
 transactionTCP.setRequest(write_sreq);
 transactionTCP.execute();
 transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] write_sreq error");
 }
 try {
 transactionSerial.setRequest(write_sreq);
 transactionSerial.execute();
 transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] write_sreq error");
 }
}
/**
 * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param read_mreq the read_mreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 ReadMultipleRegistersRequest read_mreq) throws ModbusIOException, ModbusSlaveException, ModbusException {
 try {
 transactionTCP.setRequest(read_mreq);
 transactionTCP.execute();
 read_mres = (ReadMultipleRegistersResponse) transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] read_mreq error");
 }
 try {
 
 transactionSerial.setRequest(read_mreq);
 transactionSerial.execute();
 read_mres = (ReadMultipleRegistersResponse) transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] read_mreq error");
 }
}
/**
 * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param rcreq the rcreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 ReadCoilsRequest rcreq) throws ModbusIOException, ModbusSlaveException, ModbusException {
 try {
 transactionTCP.setRequest(rcreq);
 transactionTCP.execute();
 rcres = (ReadCoilsResponse) transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] rcreq error");
 }
 try {
 transactionSerial.setRequest(rcreq);
 transactionSerial.execute();
 rcres = (ReadCoilsResponse) transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] rcreq error");
 }
}
/**
 * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param rireq the rireq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 ReadInputRegistersRequest rireq) throws ModbusIOException, ModbusSlaveException, ModbusException {
 try {
 transactionTCP.setRequest(rireq);
 transactionTCP.execute();
 rires = (ReadInputRegistersResponse) transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] rireq error");
 }
 try {
 transactionSerial.setRequest(rireq);
 transactionSerial.execute();
 rires = (ReadInputRegistersResponse) transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] rireq error");
 }
}
/**
 * Overloading method.
 *
 * @param transactionTCP the transaction tcp
 * @param transactionSerial the transaction serial
 * @param ridreq the ridreq
 * @throws ModbusIOException the modbus io exception
 * @throws ModbusSlaveException the modbus slave exception
 * @throws ModbusException the modbus exception
 */
public void transaction(ModbusTCPTransaction transactionTCP, ModbusSerialTransaction transactionSerial,
 ReadInputDiscretesRequest ridreq) throws ModbusIOException, ModbusSlaveException, ModbusException {
 try {
 transactionTCP.setRequest(ridreq);
 transactionTCP.execute();
 ridres = (ReadInputDiscretesResponse) transactionTCP.getResponse();
 } catch (Exception e) {
 System.out.println("[TCP] ridreq error");
 }
 try {
 transactionSerial.setRequest(ridreq);
 transactionSerial.execute();
 ridres = (ReadInputDiscretesResponse) transactionSerial.getResponse();
 } catch (Exception e) {
 System.out.println("[Serial] ridreq error");
 }
}
 /**
 * Gets the 16 bit int.
 *
 * @return 16bit numbers as int array
 */
public int[] get16BitInt() {
 return int16Result;
}
/**
 * Gets the 32 bit int.
 *
 * @return 32bit numbers as int array
 */
public int[] get32BitInt() {
 return int32Result;
}
/**
 * Gets the float.
 *
 * @return 32bit float numbers as float array
 */
public float[] getFloat() {
 return floatResult;
}
/**
 * Gets the round float.
 *
 * @return 32bit float numbers as rounded float array
 */
public float[] getRoundFloat() {
 return roundFloatResult;
}
/**
 * Gets the 16 bit string.
 *
 * @return 16bit numbers as String array
 */
public String[] get16BitString() {
 return string16Result;
}
/**
 * Gets the 32 bit string.
 *
 * @return 32bit numbers as String array
 */
public String[] get32BitString() {
 return string32Result;
}
/**
 * Gets the float string.
 *
 * @return 32bit float numbers as String array
 */
public String[] getFloatString() {
 return stringFloatResult;
}
/**
 * Gets the round float string.
 *
 * @return 32bit float numbers as rounded String array
 */
public String[] getRoundFloatString() {
 return roundStringFloatResult;
}
/**
 * Gets the 16 bit at index.
 *
 * @param index the index
 * @return 16bit number from int array at index
 */
public int get16BitAtIndex(int index) {
 return int16Result[index];
}
/**
 * Gets the 32 bit at index.
 *
 * @param index the index
 * @return 32bit number from int array at index
 */
public int get32BitAtIndex(int index) {
 return int32Result[index];
}
/**
 * Gets the float at index.
 *
 * @param index the index
 * @return 32bit foat number from float array at index
 */
public float getFloatAtIndex(int index) {
 return floatResult[index];
}
/**
 * Gets the round float at index.
 *
 * @param index the index
 * @return 32bit rounded float number from rounded float array at index
 */
public float getRoundFloatAtIndex(int index) {
 return roundFloatResult[index];
}
/**
 * Gets the 16 bit string at index.
 *
 * @param index the index
 * @return 16bit rounded float number from rounded String array at index
 */
public String get16BitStringAtIndex(int index) {
 return string16Result[index];
}
/**
 * Gets the 32 bit string at index.
 *
 * @param index the index
 * @return 32bit number from String array at index
 */
public String get32BitStringAtIndex(int index) {
 return string32Result[index];
}
/**
 * Gets the float string at index.
 *
 * @param index the index
 * @return 32bit float number from String array at index
 */
public String getFloatStringAtIndex(int index) {
 return stringFloatResult[index];
}
/**
 * Gets the round float string at index.
 *
 * @param index the index
 * @return 32bit rounded float number from rounded String array at index
 */
public String getRoundFloatStringAtIndex(int index) {
 return roundStringFloatResult[index];
}
/**
 * Gets the coil boolean at index.
 *
 * @param index the index
 * @return coil status from boolean array at index
 */
public Boolean getCoilBooleanAtIndex(int index) {
 return booleanCoilResult[index];
}
/**
 * Gets the coil string at index.
 *
 * @param index the index
 * @return coil status from String array at index
 */
public String getCoilStringAtIndex(int index) {
 return stringCoilResult[index];
}
/**
 * Gets the coil boolean.
 *
 * @return coil status from boolean array
 */
public boolean[] getCoilBoolean() {
 return booleanCoilResult;
}
/**
 * Gets the coil string.
 *
 * @return coil status from String array
 */
public String[] getCoilString() {
 return stringCoilResult;
}
/**
 * Gets the read bit boolean.
 *
 * @return bit status from boolean array
 */
public boolean[] getReadBitBoolean() {
 return booleanReadBitResult;
}
/**
 * Gets the read bit boolean at index.
 *
 * @param index the index
 * @return bit status from boolean array at index
 */
public boolean getReadBitBooleanAtIndex(int index) {
 return booleanReadBitResult[index];
}
/**
 * Gets the read bit string.
 *
 * @return bit status from String array
 */
public String[] getReadBitString() {
 return stringReadBitResult;
}
/**
 * Gets the read bit string bin.
 *
 * @return String binary format (01010101..)
 */
public String[] getReadBitStringBin() {
 StringBuilder[] str = new StringBuilder[toString.length];
 for (int i = 0; i < str.length; i++) {
 str[i] = new StringBuilder(toString[i]);
 int idx = str[i].length() - 4;
 while (idx > 0) {
 str[i].insert(idx, " ");
 toString[i] = str[i].toString();
 idx = idx - 4;
 }
 }
 return toString;
}
/**
 * Gets the read bit string at index.
 *
 * @param index the index
 * @return bit status from String array at index
 */
public String getReadBitStringAtIndex(int index) {
 return stringReadBitResult[index];
}
/**
 * Gets the boolean discrete input result.
 *
 * @return dicrete input status from boolean array
 */
public boolean[] getBooleanDiscreteInputResult() {
 return booleanDiscreteInputResult;
}
/**
 * Gets the boolean discrete input result at index.
 *
 * @param index the index
 * @return dicrete input status from boolean array at index
 */
public boolean getBooleanDiscreteInputResultAtIndex(int index) {
 return booleanDiscreteInputResult[index];
}
/**
 * Gets the string discrete input result.
 *
 * @return dicrete input status from String array
 */
public String[] getStringDiscreteInputResult() {
 return stringDiscreteInputResult;
}
/**
 * Gets the string discrete input result at index.
 *
 * @param index the index
 * @return dicrete input status from String array at index
 */
public String getStringDiscreteInputResultAtIndex(int index) {
 return stringDiscreteInputResult[index];
}
/**
 * Gets the int analog input registers result.
 *
 * @return analog input status from int array
 */
public int[] getIntAnalogInputRegistersResult() {
 return intAnalogInputRegistersResult;
}
/**
 * Gets the int analog input registers result at index.
 *
 * @param index the index
 * @return analog input status from int array at index
 */
public int getIntAnalogInputRegistersResultAtIndex(int index) {
 return intAnalogInputRegistersResult[index];
}
/**
 * Gets the string analog input registers result.
 *
 * @return analog input status from String array
 */
public String[] getStringAnalogInputRegistersResult() {
 return stringAnalogInputRegistersResult;
}
/**
 * Gets the string analog input registers result at index.
 *
 * @param index the index
 * @return analog input status from String array at index
 */
public String getStringAnalogInputRegistersResultAtIndex(int index) {
 return stringAnalogInputRegistersResult[index];
}

}

lang-java

AltStyle によって変換されたページ (->オリジナル) /