package com.modbus.data;
|
|
import com.serotonin.modbus4j.ModbusFactory;
|
import com.serotonin.modbus4j.ModbusMaster;
|
import com.serotonin.modbus4j.exception.ModbusInitException;
|
import com.serotonin.modbus4j.ip.IpParameters;
|
|
public class MyModbusFactory {
|
private static final int SERVER_PORT = 502; //·þÎñ¶Ë¿Ú
|
|
static ModbusFactory modbusFactory;
|
|
static {
|
if (modbusFactory == null) {
|
modbusFactory = new ModbusFactory();
|
}
|
}
|
|
/**
|
* »ñÈ¡master
|
*
|
* @return
|
* @throws ModbusInitException
|
*/
|
public static ModbusMaster getMaster(IpParameters params){
|
// modbusFactory.createRtuMaster(wapper); //RTU ÐÒé
|
// modbusFactory.createUdpMaster(params); //UDP ÐÒé
|
// modbusFactory.createAsciiMaster(wrapper); //ASCII ÐÒé
|
params.setPort(SERVER_PORT);
|
//false:¶ÌÁ¬½Ó true:³¤Á¬½Ó
|
ModbusMaster master = modbusFactory.createTcpMaster(params, true);// TCP ÐÒé
|
try {
|
//ÉèÖó¬Ê±Ê±¼ä
|
master.setTimeout(2000);
|
//ÉèÖÃÖØÁ¬´ÎÊý
|
master.setRetries(3);
|
//³õʼ»¯
|
master.init();
|
} catch (ModbusInitException e) {
|
//e.printStackTrace();
|
}
|
return master;
|
}
|
|
public static void main(String[] args) {
|
MyModbusMaster master = new MyModbusMaster("127.0.0.1", 2);
|
System.out.println(master.getMaster());
|
}
|
}
|