| | |
| | | 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);
|
| | | ModbusMaster master = modbusFactory.createTcpMaster(params, false);// TCP 协议
|
| | | try {
|
| | | master.setTimeout(2000);
|
| | | master.init();
|
| | | } catch (ModbusInitException e) {
|
| | | e.printStackTrace();
|
| | | }
|
| | | return master;
|
| | | }
|
| | | }
|
| | | 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; |
| | | } |
| | | } |