the connection has been established to modbus simulator but I am trying to read the register values from simulator and write it on console but not able to do. this code creates the connection successfully to modbus simulator but contains the syntax of readind the register values i.e requesting for register values and also response about the same but unable to fetch the register values.
below is the code i tried.
package com.jamodapp;
import java.net.InetAddress;
import net.wimpi.modbus.Modbus;
import net.wimpi.modbus.io.ModbusTCPTransaction;
import net.wimpi.modbus.msg.ReadInputDiscretesResponse;
import net.wimpi.modbus.msg.ReadMultipleRegistersRequest;
import net.wimpi.modbus.msg.ReadMultipleRegistersResponse;
import net.wimpi.modbus.net.TCPMasterConnection;
public class Connection
{
static int repeat = 1;
static TCPMasterConnection con = null;
static InetAddress addr = null;
static int port = Modbus.DEFAULT_PORT;// 502
static ModbusTCPTransaction trans = null; // the transaction
static ReadMultipleRegistersRequest req = null; // the request
static ReadMultipleRegistersResponse res = null; // the response
public static void main(String [] args) throws Exception
{
addr = InetAddress.getByName("127.0.0.1");
con = new TCPMasterConnection(addr);
con.setPort(port);
try
{
con.connect ();
} catch (Exception e) {
System.out.println("Sorry could not establish the connection");
}
if(con.isConnected())
{
System.out.println("Connection is establish");
}
// Prepare the request
ReadMultipleRegistersRequest req=new ReadMultipleRegistersRequest();
req.getHexMessage();
req = new ReadMultipleRegistersRequest( );
// Prepare the transaction
trans = new ModbusTCPTransaction(con);
trans.setRequest(req);
// Execute the transaction repeat times
trans.execute();
res = (ReadMultipleRegistersResponse) trans.getResponse();
int [] registers = new int[10] ;
int k = 0;
{
int repeat = 0;
do {
ModbusTCPTransaction trans = null;
{
ReadInputDiscretesResponse res = (ReadInputDiscretesResponse) trans.getResponse();
System.out.println("Digital Inputs Status=" + res.getDiscretes().toString());
k++;
} while (k < repeat);
//TCPMasterConnection con = null;
//6. Close the connection
//con.close();
{
registers[9] = res.getWordCount();
System.out.println(res.getWordCount());
// Close the Modbus connection
con.close();
}
}
}