连接已建立到modbus模拟器,但我试图从模拟器读取寄存器值并将其写入控制台但无法做到。 此代码成功创建了与modbus模拟器的连接,但包含readind寄存器值的语法,即请求寄存器值以及响应相同但无法获取寄存器值的语法。
下面是我试过的代码。
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();
}
}
}