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; //·þÎñ¶Ë¿Ú public static final int ModBus_TCP = 1; //ModBus-TcpЭÒé public static final int ModBus_RTU = 2; //ModBus-RtuЭÒé public static final int ModBus_UDP = 3; //ModBus-UdpЭÒé public static final int ModBus_ASCII = 4; //ModBus-AsciiЭÒé 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; } /** * »ñÈ¡master * * @return * @throws ModbusInitException */ public static ModbusMaster getMaster(MyIpParameters params,int Modbus_Type){ // modbusFactory.createRtuMaster(wapper); //RTU ЭÒé // modbusFactory.createUdpMaster(params); //UDP ЭÒé // modbusFactory.createAsciiMaster(wrapper); //ASCII ЭÒé ModbusMaster master = null; switch (Modbus_Type) { case ModBus_TCP:{ params.getParam().setPort(SERVER_PORT); master = modbusFactory.createTcpMaster(params.getParam(), true);// TCP ЭÒé }break; case ModBus_RTU:{ //master = modbusFactory.createRtuMaster(params.getWrapper()); master = modbusFactory.createRtuMaster(params.getWrapper()); }break; case ModBus_UDP:{ master = modbusFactory.createUdpMaster(params.getParam()); }break; case ModBus_ASCII:{ //modbusFactory.createAsciiMaster(wrapper); } default: break; } try { master.setTimeout(2000); master.init(); } catch (ModbusInitException e) { //e.printStackTrace(); } return master; } }