java modbus协议 com 口采集数据

参考博客
https://www.jianshu.com/p/32575c9c4e54

1、modbus4j包安装
https://github.com/infiniteautomation/modbus4j

2、文章中提到的freedomotic
中实现的SerialPortWrapper接口
https://github.com/freedomotic/freedomotic/tree/master/plugins/devices/modbus/src/main/java/com/freedomotic/plugins/devices/modbus/gateways

3、包装demo SerialPortWrapperImpl为开源项目实现的方法

package com.device.module.serialport;

import com.device.module.serialport.gateways.SerialPortWrapperImpl;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.msg.*;
import lombok.extern.log4j.Log4j2;

import java.util.Arrays;

/**
 * modbus通信包装类,初始化、连接、消息传递
 */
@Log4j2
public class ModbusWrapper {

    /**
     * COM口号
     */
    private String commPortId;
    /**
     * 波特率
     */
    private int baudRate;

    /**
     * 主站id默认1
     */
    private int defaultSlaveId = 1;

    private ModbusDataTransferProvider modbusDataTransferProvider;

    private ModbusMaster master = null;

    public ModbusWrapper(String commPortId, int baudRate, int slaveId) {
        this.commPortId = commPortId;
        this.baudRate = baudRate;
        if (slaveId <= 0) {
            this.defaultSlaveId = 1;
        }
    }

    /**
     * 设置用户消息传输接口
     *
     * @param modbusDataTransferProvider 用户需实现此接口
     */
    public void SetModbusDataTransferProvider(ModbusDataTransferProvider modbusDataTransferProvider) {
        this.modbusDataTransferProvider = modbusDataTransferProvider;
    }

    /**
     * 连接
     * 需要提供初始化连接参数
     */
    public void connAndInitMaster() {
        SerialPortWrapperImpl serialParameters = new
                SerialPortWrapperImpl(this.commPortId, this.baudRate, 8, 1, 1, 0, 0);

        // 创建ModbusFactory工厂实例
        ModbusFactory modbusFactory = new ModbusFactory();
        // 创建ModbusMaster实例
        this.master = modbusFactory.createRtuMaster(serialParameters);
        // 初始化
        try {
            this.master.init();
        } catch (ModbusInitException e) {
            log.error("ModbusWrapper.connAndInitMaster error", e.getMessage());
            throw new ModbusException("ModbusInitException err");
        }
    }

    /**
     * 读保持寄存器上的内容. 目前能用到的方法
     *
     * @param start 起始地址的偏移量
     * @param len   待读寄存器的个数
     */
    public void readHoldingRegisters(int start, int len) {
        try {
            ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(
                    this.defaultSlaveId, start, len);
            ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse) this.master
                    .send(request);
            if (response.isException()) {
                System.out.println("Exception response: message="
                        + response.getExceptionMessage());
            } else {
                System.out.println(Arrays.toString(response.getShortData()));
                short[] list = response.getShortData();
                for (int i = 0; i < list.length; i++) {
                    System.out.print(list[i] + " ");
                }
                if (modbusDataTransferProvider != null) {
                    modbusDataTransferProvider.transfer(list);
                }
            }
        } catch (ModbusTransportException e) {
            log.error("ModbusWrapper.readHoldingRegisters error", e.getMessage());
            throw new ModbusException("Modbus readHoldingRegisters err");
        }
    }

    /**
     * 销毁连接
     */
    public void destroy() {
        this.master.destroy();
    }

    /**
     * 读开关量型的输入信号 目前无用
     *
     * @param master  主站
     * @param slaveId 从站地址
     * @param start   起始偏移量
     * @param len     待读的开关量的个数
     */
    private static void readDiscreteInputTest(ModbusMaster master, int slaveId, int start, int len) {
        try {
            ReadDiscreteInputsRequest request = new ReadDiscreteInputsRequest(slaveId, start, len);
            ReadDiscreteInputsResponse response = (ReadDiscreteInputsResponse) master.send(request);
            if (response.isException())
                System.out.println("Exception response: message=" + response.getExceptionMessage());
            else
                System.out.println(Arrays.toString(response.getBooleanData()));
        } catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }


    /**
     * 批量写数据到保持寄存器
     *
     * @param master  主站
     * @param slaveId 从站地址
     * @param start   起始地址的偏移量
     * @param values  待写数据
     */
    public static void writeRegistersTest(ModbusMaster master, int slaveId, int start, short[] values) {
        try {
            WriteRegistersRequest request = new WriteRegistersRequest(slaveId, start, values);
            WriteRegistersResponse response = (WriteRegistersResponse) master.send(request);
            if (response.isException()) {
                System.out.println("Exception response: message=" + response.getExceptionMessage());
            } else {
                System.out.println("Success");
            }
        } catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }

}

4、调用

    public static void main(String[] args) {
        ModbusWrapper modbusWrapper = new ModbusWrapper("COM2", 9600, 1);
        modbusWrapper.connAndInitMaster();
        modbusWrapper.readHoldingRegisters(0, 10);
    }

5、项目构建注意项

        
        
        
            org.rxtx
            rxtx
            2.1.7
        
        
        
            org.scream3r
            jssc
            2.8.0
        
        
            com.infiniteautomation
            modbus4j
            3.0.3
        
        

你可能感兴趣的:(java modbus协议 com 口采集数据)