使用modbus4j通过串口解析modbus协议(java)

java使用modbus4j示例如下,特别注意:
如果想轮询去读数据,需要for循环调readHoldingRegistersTest(master,SLAVE_ADDRESS,0,100); 并且serialParameters.setStopBits(1); 修改为serialParameters.setStopBits(2);
 
import java.util.Arrays;

import com.serotonin.io.serial.SerialParameters;
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.ReadDiscreteInputsRequest;
import com.serotonin.modbus4j.msg.ReadDiscreteInputsResponse;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;
import com.serotonin.modbus4j.msg.WriteRegistersRequest;
import com.serotonin.modbus4j.msg.WriteRegistersResponse;

/**
 * 通过串口解析MODBUS协议
 */
public class TestModbusDemo {
    /*
     * 设定MODBUS网络上从站地址  SLAVE_ADDRESS = 1;
     * 串行波特率  BAUD_RATE = 9600;
     */
    private final static int SLAVE_ADDRESS = 1;
    private final static int BAUD_RATE = 9600;

    public static void main(String[] args) {
        SerialParameters serialParameters = new SerialParameters();
        /* 设定MODBUS通讯的串行口 */
        serialParameters.setCommPortId("COM3");
        /* 设定成无奇偶校验 */
        serialParameters.setParity(0);
        /* 设定成数据位是8位 */
        serialParameters.setDataBits(8);
        /* 设定为1个停止位 */
        serialParameters.setStopBits(1);
        /* 设定端口名称 */
        serialParameters.setPortOwnerName("COM3");
        /* 设定端口波特率 */
        serialParameters.setBaudRate(BAUD_RATE);
        /* 创建ModbusFactory工厂实例 */
        ModbusFactory modbusFactory = new ModbusFactory();
        /* 创建ModbusMaster实例 */
        ModbusMaster master = modbusFactory.createRtuMaster(serialParameters);
        /* 初始化 */
        try {
            master.init();
            readHoldingRegistersTest(master, SLAVE_ADDRESS, 0, 100);

        } catch (ModbusInitException e) {
            e.printStackTrace();

        } finally {
            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("异常消息:" + response.getExceptionMessage());
            } else {
                System.out.println(Arrays.toString(response.getBooleanData()));
            }
        } catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }


    /**
     * 读保持寄存器上的内容
     *
     * @param master  主站
     * @param slaveId 从站地址
     * @param start   起始地址的偏移量
     * @param len     待读寄存器的个数
     */
    private static void readHoldingRegistersTest(ModbusMaster master, int slaveId, int start, int len) {
        try {
            ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(slaveId, start, len);
            ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse) master.send(request);
            if (response.isException()) {
                System.out.println("异常消息:" + 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] + " ");
                }
            }
        } 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("异常消息:" + response.getExceptionMessage());
            } else {
                System.out.println("写入成功");
            }
        } catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }
}

modbus4J.jar 下载

链接:https://pan.baidu.com/s/19ogm2_hA2zUgX-afQVgJZg
提取码:ea9s

seroUtils.jar 下载

链接:https://pan.baidu.com/s/1sbjR9w4JWe5ctBcLZwb8UA
提取码:c9sv

Java串口通信依赖的jar包RXTXcomm.jar 32位与64位版本 下载

链接:https://pan.baidu.com/s/1ZH1nv9Xm90TLqEuta-g8BA
提取码:fwcd

posted on 2019-07-10 11:18  sumlen  阅读(13620)  评论(0编辑  收藏  举报

导航