package com.unis.detectionnum.server.utils;

import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.ip.IpParameters;

/**
 * @Package: com.unis.detectionnum.server.utils
 * @Author: LiuFeng
 * @Description:
 * @Date: Created in 2019/8/14
 */
public class TcpMasterUtils {

    private static ModbusFactory modbusFactory;

    static {
        if (modbusFactory == null) {
            modbusFactory = new ModbusFactory();
        }
    }

    /***
     * @Description 连接modbus主机的ip和端口
     *
     * @param ip
     * @param port
     * @return Boolean
     * @throws ModbusInitException
     * @return ModbusMaster
     */
    public static ModbusMaster getMaster(String ip, int port) throws ModbusInitException {
        IpParameters params = new IpParameters();
        params.setHost(ip);
        params.setPort(port);
        params.setEncapsulated(true);
        ModbusMaster master = modbusFactory.createTcpMaster(params, false);// TCP 协议
        //设置超时时间
        master.setTimeout(1000);
        //设置重连次数
        master.setRetries(3);
        //初始化
        master.init();

        return master;
    }
}
