1. 程式人生 > >Modbus TCP讀取暫存器資料

Modbus TCP讀取暫存器資料

modbus4j讀取暫存器資料

ModbusReadUtil讀取工具類

package cn.sync.modbus;

import org.apache.log4j.Logger;

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.ErrorResponseException;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.ip.IpParameters;
import com.serotonin.modbus4j.locator.BaseLocator;

/**
 * 
 * Modbus TCP協議讀取資料
 * @author zyl
 *
 */
public class ModbusReadUtil {
    
	private static Logger logger = Logger.getLogger(ModbusReadUtil.class);
	
	/**
	 * 單列工廠。
	 */
	static ModbusFactory modbusFactory;
	static {
		if (modbusFactory == null) {
			modbusFactory = new ModbusFactory();
		}
	}
	
	/**
	 * 獲取master 
	 * @param host  IP地址
	 * @param port  埠號
	 * @return
	 * @throws ModbusInitException
	 */
	public static ModbusMaster getMaster(String host,int port) throws ModbusInitException {
		try {
			IpParameters params = new IpParameters();
			params.setHost(host);
			params.setPort(port);
			ModbusMaster master = modbusFactory.createTcpMaster(params, false);// TCP 協議
			master.init();  //master初始化
			return master;
		} catch (Exception e) {
			logger.error("獲取master出現異常"+e);
			e.printStackTrace();
		}
         return null;
	}
	
	
	/**
	 * 讀取[03 Holding Register型別 2x]模擬量資料
	 * @param master ModbusMaster物件
	 * @param slaveId  
	 *            slave Id  裝置ID
	 * @param offset
	 *            偏移截止位置
	 * @param dataType
	 *            資料型別,來自com.serotonin.modbus4j.code.DataType
	 * @return
	 * @throws ModbusTransportException
	 *             異常
	 * @throws ErrorResponseException
	 *             異常
	 * @throws ModbusInitException
	 *             異常
	 */
	public static Number readHoldingRegister(ModbusMaster master,int slaveId, int offset, int dataType)
			throws ModbusTransportException, ErrorResponseException, ModbusInitException {
		// 03 Holding Register型別資料讀取
		BaseLocator<Number> loc = BaseLocator.holdingRegister(slaveId, offset, dataType);
		System.out.println("loc:"+loc);
		Number value =master.getValue(loc);
		System.out.println();
		return value;
   }
	
   
	/**
	 * 批量讀取使用暫存器資料
	 * @param  master ModbusMaster物件
	 * @param batchRead   批量讀取集合
	 * @throws ModbusTransportException
	 * @throws ErrorResponseException
	 * @throws ModbusInitException
	 */
	public static BatchResults<Integer> batchRead(ModbusMaster master,BatchRead<Integer> batchRead)throws Exception {
		try {
			batchRead.setContiguousRequests(false);
			BatchResults<Integer> results = master.send(batchRead);
			return results;
		} catch (Exception e) {
			logger.error("批量讀取使用暫存器資料出現異常"+e);
			e.printStackTrace();
		}
		return null;
		
	}
	
	//測試
	public static void main(String[] args) {
		try {
			ModbusMaster master=getMaster("127.0.0.1",502);
			 BatchRead<Integer> batch = new BatchRead<Integer>();

				batch.addLocator(0, BaseLocator.holdingRegister(1,1002, DataType.FOUR_BYTE_FLOAT_SWAPPED));
				batch.addLocator(1, BaseLocator.holdingRegister(1,1004, DataType.FOUR_BYTE_FLOAT_SWAPPED));
				batch.addLocator(2, BaseLocator.holdingRegister(1,1006, DataType.FOUR_BYTE_FLOAT_SWAPPED));
				batch.addLocator(3, BaseLocator.holdingRegister(1,1008, DataType.FOUR_BYTE_FLOAT_SWAPPED));
				
				BatchResults<Integer> batchRead=batchRead(master,batch);
				System.out.println(batchRead.getValue(0));
				System.out.println(batchRead.getValue(1));
				System.out.println(batchRead.getValue(2));
				System.out.println(batchRead.getValue(3));
				//DataType.FOUR_BYTE_FLOAT_SWAPPED  float高低位資料處理
				Number v031 = readHoldingRegister(master,1,1010, DataType.FOUR_BYTE_FLOAT_SWAPPED);// 注意,float
				System.out.println("v031:"+v031);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	
   
}

程式碼以及依賴JAR下載