package com.unis.detectionnum.server.utils;

import com.serotonin.modbus4j.exception.ErrorResponseException;
import com.serotonin.modbus4j.locator.BaseLocator;
import com.serotonin.modbus4j.msg.*;
import com.serotonin.modbus4j.sero.util.queue.ByteQueue;

import io.netty.util.ReferenceCountUtil;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.digitalpetri.modbus.codec.Modbus;
import com.serotonin.modbus4j.BatchRead;
import com.serotonin.modbus4j.BatchResults;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.code.DataType;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.ip.IpParameters;

/**
 * @Package: com.unis.detectionnum.server.utils
 * @Author: LiuFeng
 * @Description:modbus4j 工具类
 * @Date: Created in 2019/8/14
 */
public class Modbus4jUtils {

    static Log log = LogFactory.getLog(Modbus4jUtils.class);

    /***
     * @Description 写[03 Holding Register(4x)] 写一个 function ID = 0x0006
     *
     * @param ip
     * @param port
     * @param slaveId
     * @param writeOffset
     * @param value
     * @return Boolean
     * @throws ModbusTransportException
     * @throws ModbusInitException
     */
    public static boolean writeRegister(String ip, int port,int slaveId, int writeOffset, int value)
            throws ModbusTransportException, ModbusInitException {
    	ModbusFactory modbusFactory = new ModbusFactory();  
        // 设备ModbusTCP的Ip与端口，如果不设定端口则默认为502  
        IpParameters params = new IpParameters();  
        params.setHost(ip); 
        params.setPort(port);  
        
        ModbusMaster tcpMaster =   modbusFactory.createTcpMaster(params, true);  
        tcpMaster.init();
        // 创建请求对象,写单个寄存器
        WriteRegisterRequest request = new WriteRegisterRequest(slaveId, writeOffset, value);
        WriteRegisterResponse response = (WriteRegisterResponse) tcpMaster.send(request);
        destroy(tcpMaster);
        if (response.isException()) {
            log.error(response.getExceptionMessage());
            return false;
        } else {
            return true;
        }

    }

    /**
     * 读取[03 Holding Register类型 2x]模拟量数据
     *
     * @param ip
     * @param port
     * @param slaveId 从站地址
     * @param start 起始地址偏移量
     * @param readLenth 待读寄存器个数
     * @return ByteQueue
     * @throws ModbusTransportException 异常
     * @throws ModbusInitException 
     */
    public static ByteQueue readHoldingRegisters(String ip, int port,int slaveId,int start, int readLenth) throws ModbusTransportException, ModbusInitException {

    	ModbusFactory modbusFactory = new ModbusFactory();  
        // 设备ModbusTCP的Ip与端口，如果不设定端口则默认为502  
        IpParameters params = new IpParameters();  
        params.setHost(ip); 
        params.setPort(port);  
        
        ModbusMaster tcpMaster =   modbusFactory.createTcpMaster(params, true);  
        tcpMaster.init();
        //功能码03   读取保持寄存器的值
        ModbusRequest modbusRequest = new ReadHoldingRegistersRequest(slaveId, start, readLenth);
        ModbusResponse modbusResponse = tcpMaster.send(modbusRequest);

        ByteQueue byteQueue= new ByteQueue(1024);
        modbusResponse.write(byteQueue);
        destroy(tcpMaster);
        return byteQueue;
    }

    /**
     * 读取[03 Holding Register类型 2x]模拟量数据
     *
     * @param ip
     * @param port
     * @param slaveId 从站地址
     * @param offset 读取地址
     * @param dataType 数据类型,来自com.serotonin.modbus4j.code.DataType
     * @return Number
     * @throws ModbusTransportException 异常
     * @throws ErrorResponseException 异常
     * @throws ModbusInitException 异常
     */
    public static Number readHoldingRegister(String ip, int port,int slaveId, int offset, int dataType)
            throws ModbusTransportException, ErrorResponseException, ModbusInitException {
    	ModbusFactory modbusFactory = new ModbusFactory();  
        // 设备ModbusTCP的Ip与端口，如果不设定端口则默认为502  
        IpParameters params = new IpParameters();  
        params.setHost(ip); 
        params.setPort(port);  
        
        ModbusMaster tcpMaster =   modbusFactory.createTcpMaster(params, true);  
        tcpMaster.init();  
       
        // 03 Holding Register类型数据读取
        BaseLocator<Number> loc = BaseLocator.holdingRegister(slaveId, offset, dataType);
        Number value = tcpMaster.getValue(loc);
        destroy(tcpMaster);
        return value;
    }
    
    /**
     * 写入数字类型的模拟量（如:写入Float类型的模拟量、Double类型模拟量、整数类型Short、Integer、Long）
     * 
     * @param slaveId
     * @param offset
     * @param value
     *            写入值,Number的子类,例如写入Float浮点类型,Double双精度类型,以及整型short,int,long
     * @param registerCount
     *            ,com.serotonin.modbus4j.code.DataType
     * @throws ModbusTransportException
     * @throws ErrorResponseException
     * @throws ModbusInitException
     */
    public static void writeHoldingRegister(String ip, int port,int slaveId, int offset, Number value, int dataType)
            throws ModbusTransportException, ErrorResponseException, ModbusInitException {
        // 获取master
    	ModbusFactory modbusFactory = new ModbusFactory();  
        // 设备ModbusTCP的Ip与端口，如果不设定端口则默认为502  
        IpParameters params = new IpParameters();  
        params.setHost(ip); 
        params.setPort(port);  
        
        ModbusMaster tcpMaster =   modbusFactory.createTcpMaster(params, true);  
        tcpMaster.init();  
        // 类型
        BaseLocator<Number> locator = BaseLocator.holdingRegister(slaveId, offset, dataType);
        tcpMaster.setValue(locator, value);
        destroy(tcpMaster);
    }
    
    /**
     * 批量读取 可以批量读取不同寄存器中数据
     */
    public static BatchResults<Integer> batchRead(String ip, int port,int slaveId) throws ModbusTransportException, ErrorResponseException, ModbusInitException {
 
    	// 获取master
    	ModbusFactory modbusFactory = new ModbusFactory();  
        // 设备ModbusTCP的Ip与端口，如果不设定端口则默认为502  
        IpParameters params = new IpParameters();  
        params.setHost(ip); 
        params.setPort(port);  
        
        ModbusMaster tcpMaster =   modbusFactory.createTcpMaster(params, true);  
        tcpMaster.init();  
        
        BatchRead<Integer> batch = new BatchRead<Integer>();
        batch.addLocator(0, BaseLocator.holdingRegister(1, 1, DataType.TWO_BYTE_INT_SIGNED));
        batch.addLocator(1, BaseLocator.inputStatus(1, 0));
        batch.setContiguousRequests(true);
        BatchResults<Integer> results = tcpMaster.send(batch);
        destroy(tcpMaster);
        return results;
    }
 
    
    /***
     * 释放资源
     */
    public static void destroy(ModbusMaster tcpMaster) {
        if (tcpMaster != null) {
        	tcpMaster.destroy();
        }
        Modbus.releaseSharedResources();
    }
    
    public static void main(String[] args) throws ModbusTransportException, ModbusInitException, ErrorResponseException {
    	//writeRegister("127.0.0.1", 502, 1, 0, 1234);
    	Number number = readHoldingRegister("127.0.0.1",502,1,0,DataType.TWO_BYTE_INT_SIGNED);
    	System.out.println(number.intValue());
    	
    	ByteQueue byteQueue = readHoldingRegisters("127.0.0.1",502,1,0,3);
    	System.out.println(byteQueue.toString());
	}
}
