whyclxw
2020-11-02 f8b7ca9bc6b51c137053f16c1c7150a11aba13c4
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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, true);// TCP 协议
        try {
             //设置超时时间
            master.setTimeout(1000);
            //设置重连次数
            master.setRetries(3);
            //初始化
            master.init();
        } catch (ModbusInitException e) {
            //e.printStackTrace();
        }
        return master;
    }
}