whyclj
2021-01-05 64aba412c2b739d67795b14a3cae069d311697f9
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
44
45
46
47
48
49
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());
    }
}