Created
May 14, 2015 09:41
-
-
Save zho/8d5f473fb15f93ddff5c to your computer and use it in GitHub Desktop.
J2mod / Jamod read 4 TCP slave sample
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.ghgande.j2mod.modbus.io.ModbusTCPTransaction; | |
import com.ghgande.j2mod.modbus.msg.ReadMultipleRegistersRequest; | |
import com.ghgande.j2mod.modbus.msg.ReadMultipleRegistersResponse; | |
import com.ghgande.j2mod.modbus.net.TCPMasterConnection; | |
import java.net.InetAddress; | |
import java.util.logging.Level; | |
import java.util.logging.Logger; | |
/** | |
* | |
* @author zho | |
*/ | |
public class TCPModbus { | |
/* The important instances of the classes mentioned before */ | |
protected static TCPMasterConnection con = null; //the conection | |
protected static ModbusTCPTransaction trans = null; //the transaction | |
protected static ReadMultipleRegistersRequest req = null; //the request | |
protected static ReadMultipleRegistersResponse res = null; //the response | |
/* Variables for storing the parameters */ | |
protected static InetAddress addr = null; //the slave's address | |
protected static final int port = 3000; | |
protected static final int ref = Integer.parseInt("011E", 16); //the reference; offset where to start reading from | |
protected static final int count = 1; //the number of DI's to read | |
protected static final int repeat = 1; //a loop for repeating the transaction | |
/** | |
* @param args the command line arguments | |
*/ | |
public static void callTCPModbus() { | |
try { | |
addr = InetAddress.getByName("127.0.0.1"); | |
//2. Open the connection | |
con = new TCPMasterConnection(addr); | |
con.setPort(port); | |
con.connect(); | |
req = new ReadMultipleRegistersRequest(ref, count); | |
trans = new ModbusTCPTransaction(con); | |
for (int a = 0; a < 4; a++) { | |
req.setUnitID(a); | |
trans.setRequest(req); | |
trans.execute(); | |
res = (ReadMultipleRegistersResponse) trans.getResponse(); | |
for (int n = 0; n < res.getWordCount(); n++) { | |
System.out.println("Word " + a + "=" + res.getRegisterValue(n)); | |
} | |
} | |
//6. Close the connection | |
con.close(); | |
} catch (Exception ex) { | |
Logger.getLogger(ModbusTest.class.getName()).log(Level.SEVERE, null, ex); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment