私.Modbus测试_ZC03_rtu,ascii,tcp

ZC:另外一些信息在 “Modbus资料 - codeskill_android - 博客园.html”(https://www.cnblogs.com/codeskilla/p/9998416.html

1、文章:modbus4j,rtu,ascii,tcp_ip传输模式 - 狂野的河 - CSDN博客.html(https://blog.csdn.net/u013150916/article/details/78065479?locationNum=9&fps=1#commentBox

2、包:路径:“...\ZC_IDE\Java_3rd\modbus_java\02_新一点的\Mango Automation\”

  JAR:主要都是来自 m2m2-modbus-1.5.4.zip 中的 lib文件夹

  源码:没有去找对应版本jar的源码(也不知道能不能找到)

3、测试代码:

package com.test.modbus;

import java.util.Arrays;

import org.junit.Test;

import com.serotonin.modbus4j.BasicProcessImage;
import com.serotonin.modbus4j.BatchRead;
import com.serotonin.modbus4j.BatchResults;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.ModbusSlaveSet;
import com.serotonin.modbus4j.ProcessImage;
import com.serotonin.modbus4j.ProcessImageListener;
import com.serotonin.modbus4j.code.DataType;
import com.serotonin.modbus4j.exception.ErrorResponseException;
import com.serotonin.modbus4j.exception.IllegalDataAddressException;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.ip.IpParameters;
import com.serotonin.modbus4j.locator.BaseLocator;
import com.serotonin.modbus4j.msg.ReadCoilsRequest;
import com.serotonin.modbus4j.msg.ReadCoilsResponse;
import com.serotonin.modbus4j.msg.ReadDiscreteInputsRequest;
import com.serotonin.modbus4j.msg.ReadDiscreteInputsResponse;
import com.serotonin.modbus4j.msg.ReadExceptionStatusRequest;
import com.serotonin.modbus4j.msg.ReadExceptionStatusResponse;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;
import com.serotonin.modbus4j.msg.ReadInputRegistersRequest;
import com.serotonin.modbus4j.msg.ReadInputRegistersResponse;
import com.serotonin.modbus4j.msg.ReportSlaveIdRequest;
import com.serotonin.modbus4j.msg.ReportSlaveIdResponse;
import com.serotonin.modbus4j.msg.WriteCoilRequest;
import com.serotonin.modbus4j.msg.WriteCoilResponse;
import com.serotonin.modbus4j.msg.WriteCoilsRequest;
import com.serotonin.modbus4j.msg.WriteCoilsResponse;
import com.serotonin.modbus4j.msg.WriteMaskRegisterRequest;
import com.serotonin.modbus4j.msg.WriteMaskRegisterResponse;
import com.serotonin.modbus4j.msg.WriteRegisterRequest;
import com.serotonin.modbus4j.msg.WriteRegisterResponse;
import com.serotonin.modbus4j.msg.WriteRegistersRequest;
import com.serotonin.modbus4j.msg.WriteRegistersResponse;

import com.serotonin.io.serial.SerialParameters;

public class MasterTest
{

    public static void main(String[] args) throws Exception
    {

            //TCP传输方式
//            ModbusMaster master = getTcpMaster();
            //RTU传输方式
            ModbusMaster master = getRtuMaster();
            //ASCII传输模式
//            ModbusMaster master = getAsiiMaster();
//           ModbusMaster master = modbusFactory.createUdpMaster(ipParameters);

        try {
            //初始化
            //设置超时时间
            master.setTimeout(500);
            //设置重连次数
            master.setRetries(1);
            master.init();
            //设置从站ID
            int slaveId = 1;

            //测试校验
//            Timer timer = new Timer();
//            timer.schedule(new TimerTask() {
//
//                @Override
//                public void run() {
//                    //RTU
//                    ModbusMaster master = getRtuMaster();
//                    //ASCII
////                    ModbusMaster master = getAsiiMaster();
//                    try {
//                        master.init();
//                        readCoilTest(master, 1, 0, 10);
//                    } catch (ModbusInitException e) {
//                        e.printStackTrace();
//                    } finally {
//                        master.destroy();
//                    }
//                }
//            }, 100, 1000);

            //------------------读---------------
            //读取开关量状态   01
//            readCoilTest(master, slaveId, 0, 5);
            //读取外部设备输入开关量状态  02
//            readDiscreteInputTest(master, slaveId, 0, 10);
            //读取保持寄存器数据 03
//            readHoldingRegistersTest(master, slaveId, 0, 10);
            //读取外围设备输入的数据 04
//            readInputRegistersTest(master, slaveId, 0, 10);
            //------------------写---------------
            //开关量写单个数据 05
//            writeCoilTest(master, slaveId, 9, true);
            //开关量写入多个数据 15
//            writeCoilsTest(master, slaveId, 0, new boolean[] {true, true, true, true, true});
            //写入单个模拟量数据 06
//            writeRegisterTest(master, slaveId, 0, 100);
            //写入多个模拟量数据 16
//            writeRegistersTest(master, slaveId, 0, new short[] {1, 10, 100, 1000, 10000, (short) 65534});

            //批量读取
//               bathRead(master, slaveId);
            //根据类型写
               writeValue(master);
            //异常
//               readExceptionStatusTest(master, slaveId);

        }
        finally {
            master.destroy();
        }
    }

    /**
     * @Description: 根据类型写数据
     * @param master
     * @throws ModbusTransportException
     * @throws ErrorResponseException
     */
    public static void writeValue(ModbusMaster master) throws ModbusTransportException, ErrorResponseException {

//        BaseLocator<?> createLocator = StringLocator.createLocator(1, 1, DataType.TWO_BYTE_INT_UNSIGNED, 1, 2);

//        BaseLocator<Number> hr1 = BaseLocator.holdingRegister(1, 0, DataType.TWO_BYTE_INT_UNSIGNED);
//        BaseLocator<Number> hr1 = BaseLocator.holdingRegister(1, 0, DataType.TWO_BYTE_INT_UNSIGNED_SWAPPED);
//        BaseLocator<Number> hr1 = BaseLocator.holdingRegister(1, 0, DataType.TWO_BYTE_INT_UNSIGNED);
//        BaseLocator<Number> hr1 = BaseLocator.holdingRegister(1, 0, DataType.FOUR_BYTE_INT_UNSIGNED);
        //测试高低位0x12345678
//        BaseLocator<Number> hr1 = BaseLocator.holdingRegister(1, 0, DataType.FOUR_BYTE_INT_UNSIGNED);
//        BaseLocator<Number> hr1 = BaseLocator.holdingRegister(1, 0, DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED);
//        BaseLocator<Number> hr1 = BaseLocator.inputRegister(1, 0, DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED);
        BaseLocator<Number> hr1 = BaseLocator.holdingRegister(1, 0, DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED);// ZC: 上面那样会报错,我改成的这样
//        BaseLocator<Number> hr2 = BaseLocator.holdingRegister(1, 0, DataType.TWO_BYTE_INT_UNSIGNED);
        //测试浮点数
//        BaseLocator<Number> hr2 = BaseLocator.holdingRegister(1, 0, DataType.FOUR_BYTE_INT_UNSIGNED);
//        master.setValue(hr2, 0x3F800000);

         master.setValue(hr1, 0x12345678);

    }

    /**
     * @Description: 批量读取    可以批量读取不同寄存器中数据
     * @param master
     * @param slaveId
     * @throws ModbusTransportException
     * @throws ErrorResponseException
     */
    public static void bathRead(ModbusMaster master, int slaveId)
            throws ModbusTransportException, ErrorResponseException {

            BatchRead<Number> batch = new BatchRead<Number>();

            //****************批量读取不同寄存器中的单个数据********************
            //读取线圈状态开关量
//               batch.addLocator(1, BaseLocator.coilStatus(slaveId, 0));
               //读取输入状态 开关量
//               batch.addLocator(2, BaseLocator.inputStatus(slaveId, 0));

               //读取保持寄存器数据
               //根据设置的数据类型读取
//               batch.addLocator(3, BaseLocator.holdingRegister(slaveId, 0, DataType.TWO_BYTE_INT_UNSIGNED));
               //读取整形中16位中某一位的布尔值
//               batch.addLocator(3.1, BaseLocator.holdingRegisterBit(slaveId, 0, 0));

               //读取输入寄存器数据
               //根据设置的数据类型读取
//               batch.addLocator(4, BaseLocator.inputRegister(slaveId, 0, DataType.TWO_BYTE_INT_UNSIGNED));
             //读取整形中16位中某一位的布尔值
//               batch.addLocator(4.1, BaseLocator.inputRegisterBit(slaveId, 0, 0));

               //高低字节颠倒
               batch.addLocator(1, BaseLocator.holdingRegister(slaveId, 0, DataType.FOUR_BYTE_INT_UNSIGNED_SWAPPED));
               //高低字节不颠倒
//               batch.addLocator(1, BaseLocator.holdingRegister(slaveId, 0, DataType.FOUR_BYTE_INT_UNSIGNED));
               //读取浮点数
//               batch.addLocator(1, BaseLocator.holdingRegister(slaveId, 0, DataType.FOUR_BYTE_FLOAT));
             BatchResults<Number> results = master.send(batch);
//             System.out.println("批量读取1:--" + results.getValue(1));
//             System.out.println("批量读取2:--" + results.getValue(2));
//             System.out.println("批量读取3:--" + results.getValue(3));
//             System.out.println("批量读取3.1:--" + results.getValue(3.1));
//             System.out.println("批量读取3.2:--" + results.getValue(3.2));
//             System.out.println("批量读取4:--" + results.getValue(4));
//             System.out.println("批量读取4.1:--" + results.getValue(4.1));
             //高低字节颠倒
             System.out.println(Long.toHexString((long) results.getValue(1)));

    }

    /**
     * @Description: 读取开关量
     * @param master 主站实例
     * @param slaveId 从站ID
     * @param start 起始位
     * @param len 读取的长度
     */
    public static void readCoilTest(ModbusMaster master, int slaveId, int start, int len) {
        try {
            ReadCoilsRequest request = new ReadCoilsRequest(slaveId, start, len);
            ReadCoilsResponse response = (ReadCoilsResponse) master.send(request);

            if (response.isException())
                System.out.println("Exception response: message=" + response.getExceptionMessage());
            else
                System.out.println("功能码:1--" + Arrays.toString(response.getBooleanData()));
        }
        catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 读取外围设备输入的开关量
     * @param master 主站实例
     * @param slaveId 从站ID
     * @param start 起始位
     * @param len 长度
     */
    public 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("功能码:2--" + Arrays.toString(response.getBooleanData()));
        }
        catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 读取保持寄存器数据
     * @param master 主站实例
     * @param slaveId 从站ID
     * @param start 起始位
     * @param len 长度
     */
    public 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("Exception response: message=" + response.getExceptionMessage());
            else
                System.out.println("功能码:3--" + Arrays.toString(response.getShortData()));
        }
        catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 读取外围设备输入的数据
     * @param master 主站实例
     * @param slaveId 从站ID
     * @param start 起始位
     * @param len 长度
     */
    public static void readInputRegistersTest(ModbusMaster master, int slaveId, int start, int len) {
        try {
            ReadInputRegistersRequest request = new ReadInputRegistersRequest(slaveId, start, len);
            ReadInputRegistersResponse response = (ReadInputRegistersResponse) master.send(request);

            if (response.isException())
                System.out.println("Exception response: message=" + response.getExceptionMessage());
            else
                System.out.println("功能码:4--" + Arrays.toString(response.getShortData()));
        }
        catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 写开关量数据
     * @param master
     * @param slaveId 从站ID
     * @param offset 偏移量
     * @param value 写入的值
     */
    public static void writeCoilTest(ModbusMaster master, int slaveId, int offset, boolean value) {
        try {
            WriteCoilRequest request = new WriteCoilRequest(slaveId, offset, value);
            WriteCoilResponse response = (WriteCoilResponse) master.send(request);

            if (response.isException())
                System.out.println("Exception response: message=" + response.getExceptionMessage());
            else
                System.out.println("功能码:1,写入单个数据成功!");
        }
        catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 保持寄存器,写入单个数据
     * @param master
     * @param slaveId 从站ID
     * @param offset 偏移量
     * @param value
     */
    public static void writeRegisterTest(ModbusMaster master, int slaveId, int offset, int value) {
        try {
            WriteRegisterRequest request = new WriteRegisterRequest(slaveId, offset, value);
            WriteRegisterResponse response = (WriteRegisterResponse) master.send(request);

            if (response.isException())
                System.out.println("Exception response: message=" + response.getExceptionMessage());
            else
                System.out.println("功能码:3,写入单个模拟量数据成功!");
        }
        catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 读取异常状态
     * @param master
     * @param slaveId
     */
    public static void readExceptionStatusTest(ModbusMaster master, int slaveId) {
        try {
            ReadExceptionStatusRequest request = new ReadExceptionStatusRequest(slaveId);
            ReadExceptionStatusResponse response = (ReadExceptionStatusResponse) master.send(request);

            if (response.isException())
                System.out.println("Exception response: message=" + response.getExceptionMessage());
            else
                System.out.println(response.getExceptionStatus());
        }
        catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }

    public static void reportSlaveIdTest(ModbusMaster master, int slaveId) {
        try {
            ReportSlaveIdRequest request = new ReportSlaveIdRequest(slaveId);
            ReportSlaveIdResponse response = (ReportSlaveIdResponse) master.send(request);

            if (response.isException())
                System.out.println("Exception response: message=" + response.getExceptionMessage());
            else
                System.out.println(Arrays.toString(response.getData()));
        }
        catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 保持寄存器写多个数据
     * @param master
     * @param slaveId 从站ID
     * @param start 起始位置
     * @param values 数值
     */
    public static void writeCoilsTest(ModbusMaster master, int slaveId, int start, boolean[] values) {
        try {
            WriteCoilsRequest request = new WriteCoilsRequest(slaveId, start, values);
            WriteCoilsResponse response = (WriteCoilsResponse) master.send(request);

            if (response.isException())
                System.out.println("Exception response: message=" + response.getExceptionMessage());
            else
                System.out.println("功能码:1,写入多个数据成功!");
        }
        catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }

    /**
     * @Description: 保持寄存器写入多个模拟量数据
     * @param master
     * @param slaveId 从站ID
     * @param start modbus起始位置
     * @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("功能码:3,写入多个模拟量数据成功!");
        }
        catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }

    public static void writeMaskRegisterTest(ModbusMaster master, int slaveId, int offset, int and, int or) {
        try {
            WriteMaskRegisterRequest request = new WriteMaskRegisterRequest(slaveId, offset, and, or);
            WriteMaskRegisterResponse response = (WriteMaskRegisterResponse) master.send(request);

            if (response.isException())
                System.out.println("Exception response: message=" + response.getExceptionMessage());
            else
                System.out.println("Success");
        }
        catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }

    /**
     * @return
     * @Description: 获取AsiiMaster
     */
    public static ModbusMaster getAsiiMaster(){
        SerialParameters serialParameters = new SerialParameters();
        // 设定MODBUS通讯的串行口
        serialParameters.setCommPortId("COM4");
        // 设置端口波特率
        serialParameters.setBaudRate(9600);
        //硬件之间输入流应答控制
        serialParameters.setFlowControlIn(0);
        //硬件之间输出流应答控制
        serialParameters.setFlowControlOut(0);
        //设定数据位的位数  RTU:8位    ASCII:7位
        serialParameters.setDataBits(7);
        //停止位的位数,如果无奇偶校验为2,有奇偶校验为1
        serialParameters.setParity(2);
        //停止位的位数,如果无奇偶校验为2,有奇偶校验为1
        serialParameters.setStopBits(1);
        // 设置端口名称
        serialParameters.setPortOwnerName("ASCII");
        // 创建ModbusMaster工厂实例
        return new ModbusFactory().createAsciiMaster(serialParameters);
    }

    /**
     * @Description: 获取AsiiSalve
     * @return
     */
    public static ModbusSlaveSet getAsciiSalve(){
        SerialParameters serialParameters = new SerialParameters();
        // 设定MODBUS通讯的串行口
        serialParameters.setCommPortId("COM4");
        // 设置端口波特率
        serialParameters.setBaudRate(9600);
        //硬件之间输入流应答控制
        serialParameters.setFlowControlIn(0);
        //硬件之间输出流应答控制
        serialParameters.setFlowControlOut(0);
        //设定数据位的位数  RTU:8位    ASCII:7位
        serialParameters.setDataBits(7);
        //奇偶校验位  无校验:0 奇校验:1 偶校验:2
        serialParameters.setParity(2);
        //停止位的位数,如果无奇偶校验为2,有奇偶校验为1
        serialParameters.setStopBits(1);
        // 设置端口名称
        serialParameters.setPortOwnerName("ASCII");
        // 创建ModbusMaster工厂实例
        return new ModbusFactory().createAsciiSlave(serialParameters);
    }
    /**
     * @return
     * @Description: 获取RTUMaster
     */
    public static ModbusMaster getRtuMaster(){
        SerialParameters serialParameters = new SerialParameters();
//         TestSerialPortWrapper portWrapper = new TestSerialPortWrapper("COM4", 9600, 0, 0, 8, 1, 2);
        // 设定MODBUS通讯的串行口
        serialParameters.setCommPortId("COM4");
        // 设置端口波特率
        serialParameters.setBaudRate(9600);
        //硬件之间输入流应答控制
        serialParameters.setFlowControlIn(0);
        //硬件之间输出流应答控制
        serialParameters.setFlowControlOut(0);
        //设定数据位的位数  RTU:8位    ASCII:7位
        serialParameters.setDataBits(8);
        //奇偶校验位  无校验:0 奇校验:1 偶校验:2
        serialParameters.setParity(2);
        //停止位的位数,如果无奇偶校验为2,有奇偶校验为1
        serialParameters.setStopBits(1);
        // 设置端口名称
        serialParameters.setPortOwnerName("RTU");
        // 创建ModbusMaster工厂实例
        return new ModbusFactory().createRtuMaster(serialParameters);
    }

    /**
     * @Description: 创建TcpMaster
     * @return
     */
    public static ModbusMaster getTcpMaster() {
        IpParameters ipParameters = new IpParameters();
        //设置IP
        ipParameters.setHost("localhost");
        //设置端口 默认为502
        ipParameters.setPort(502);
        // 创建ModbusMaster工厂实例
        return new ModbusFactory().createTcpMaster(ipParameters, true);
    }

    /**
     * @Description: IO盒测试
     * @throws ModbusInitException
     * @throws ModbusTransportException
     * @throws ErrorResponseException
     */
    @Test
    public void konnadTest() throws ModbusInitException, ModbusTransportException, ErrorResponseException{
        IpParameters params = new IpParameters();
        params.setHost("172.16.16.205");
        params.setPort(502);
        //获取主站
        ModbusMaster master = new ModbusFactory().createTcpMaster(params, false);
        master.init();
        //读取MAC地址
        ReadHoldingRegistersRequest request = new ReadHoldingRegistersRequest(1, 0, 3);
        ReadHoldingRegistersResponse response = (ReadHoldingRegistersResponse) master.send(request);
//        System.out.println("MAC地址" + ConversionUtil.getHexString(response.getData()));
        // ZC: 上面的 ConversionUtil貌似是 博主自己写的类,就先注释掉了

//        WriteRegisterRequest request1 = new WriteRegisterRequest(1, 1056, 0);
//        ModbusResponse response1 = master.send(request1);
//        if (response1.isException())
//            System.out.println("Exception response: message=" + response1.getExceptionMessage());
//        else
//            System.out.println("功能码:3,写入多个模拟量数据成功!");
        //写数据 DO0的状态  0x0400  I/O盒实际为DO1
//        WriteRegisterRequest request1 = new WriteRegisterRequest(1, 1024, 1);
//        master.send(request1);
        //写数据 DO1上电的状态  0x0411
//        WriteRegistersRequest request2 = new WriteRegistersRequest(1, 1040, new short[] {1, 1} );
//        master.send(request2);
        //读取 0x0411状态  为上电后的状态
//        ReadHoldingRegistersRequest request3 = new ReadHoldingRegistersRequest(1, 1040, 7);
//        ReadHoldingRegistersResponse response3 = (ReadHoldingRegistersResponse) master.send(request3);
//        System.out.println(Arrays.toString(response3.getShortData()));

    }

    /**
     * @Description: 创建modbus服务端  从站
     */
    @Test
    public void createSalve(){
        //创建modbus工厂
        ModbusFactory modbusFactory = new ModbusFactory();
        //创建TCP服务端
        final ModbusSlaveSet salve = modbusFactory.createTcpSlave(false);
        //创建ASCII服务端
//        final ModbusSlaveSet salve = getAsciiSalve();
        //向过程影像区添加数据
        salve.addProcessImage(getModscanProcessImage(1));

         new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        salve.start();
                    }
                    catch (ModbusInitException e) {
                        e.printStackTrace();
                    }
                }
            }).start();

         while (true) {
                synchronized (salve) {
                    try {
                        salve.wait(200);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

                for (ProcessImage processImage : salve.getProcessImages())
                    try {
                        updateProcessImage((BasicProcessImage) processImage);
                    } catch (IllegalDataAddressException e) {
                        e.printStackTrace();
                    }
            }
    }

     /**
     * @Description: 创建寄存器
     * @param slaveId
     * @return
     */
    public static BasicProcessImage getModscanProcessImage(int slaveId) {
         BasicProcessImage processImage = new BasicProcessImage(slaveId);
         processImage.setInvalidAddressValue(Short.MIN_VALUE);

         //创建可读写开关量区
         processImage.setCoil(0, true);
         processImage.setCoil(1, false);
         processImage.setCoil(2, true);
         processImage.setCoil(3, true);
         processImage.setCoil(5, true);
         processImage.setCoil(6, true);
         processImage.setCoil(7, true);
         processImage.setCoil(8, true);
         processImage.setCoil(9, true);

         //创建只读开关量区
         processImage.setInput(0, false);
         processImage.setInput(1, false);
         processImage.setInput(2, true);
         processImage.setInput(3, false);
         processImage.setInput(4, true);
         processImage.setInput(5, true);
         processImage.setInput(6, true);
         processImage.setInput(7, true);
         processImage.setInput(8, true);
         processImage.setInput(9, true);

         //创建模拟量保持寄存器
         processImage.setHoldingRegister(0, (short) 1);
         processImage.setHoldingRegister(1, (short) 10);
         processImage.setHoldingRegister(2, (short) 100);
         processImage.setHoldingRegister(3, (short) 1000);
         processImage.setHoldingRegister(4, (short) 10000);
         processImage.setHoldingRegister(5, (short) 10000);
         processImage.setHoldingRegister(6, (short) 10000);
         processImage.setHoldingRegister(7, (short) 10000);
         processImage.setHoldingRegister(8, (short) 10000);
         processImage.setHoldingRegister(9, (short) 10000);

         //创建模拟量只读寄存器
         processImage.setInputRegister(0, (short) 10000);
         processImage.setInputRegister(1, (short) 1000);
         processImage.setInputRegister(2, (short) 100);
         processImage.setInputRegister(3, (short) 10);
         processImage.setInputRegister(4, (short) 1);
         processImage.setInputRegister(5, (short) 1);
         processImage.setInputRegister(6, (short) 1);
         processImage.setInputRegister(7, (short) 1);
         processImage.setInputRegister(8, (short) 1);
         processImage.setInputRegister(9, (short) 1);

         processImage.addListener(new BasicProcessImageListener());

        return processImage;
     }

    /**
     * @Description: 客户端修改本地寄存器的数据
     * @author-lsh
     * @date 2017年9月13日 下午5:47:30
     */
    public static class BasicProcessImageListener implements ProcessImageListener {
            @Override
            public void coilWrite(int offset, boolean oldValue, boolean newValue) {
                System.out.println("Coil at " + offset + " was set from " + oldValue + " to " + newValue);
            }

            @Override
            public void holdingRegisterWrite(int offset, short oldValue, short newValue) {
                // Add a small delay to the processing.
                //            try {
                //                Thread.sleep(500);
                //            }
                //            catch (InterruptedException e) {
                //                // no op
                //            }
                System.out.println("HR at " + offset + " was set from " + oldValue + " to " + newValue);
            }
        }

     /**
     * @Description: 更新寄存器的数据
     * @param processImage
     * @throws IllegalDataAddressException
     */
    static void updateProcessImage(BasicProcessImage processImage) throws IllegalDataAddressException {
            processImage.setInput(0, !processImage.getInput(0));
            processImage.setInput(1, !processImage.getInput(1));

//            processImage.setNumeric(RegisterRange.INPUT_REGISTER, 20, DataType.FOUR_BYTE_FLOAT, ir1Value += 0.01);
    //
//            short hr1Value = processImage.getNumeric(RegisterRange.HOLDING_REGISTER, 80, DataType.TWO_BYTE_BCD)
//                    .shortValue();
//            processImage.setNumeric(RegisterRange.HOLDING_REGISTER, 80, DataType.TWO_BYTE_BCD, hr1Value + 1);
        }
    @Test
    public void StringTest(){
        String a = "abc123456789";
        char[] charArray = a.toCharArray();
        System.err.println(Arrays.toString(charArray));
    }
}

4、

5、

原文地址:https://www.cnblogs.com/codeskilla/p/10017722.html

时间: 2024-10-07 21:17:26

私.Modbus测试_ZC03_rtu,ascii,tcp的相关文章

私.Modbus测试_ZC02_串口方式

ZC:另外一些信息在 "Modbus资料 - codeskill_android - 博客园.html"(https://www.cnblogs.com/codeskilla/p/9998416.html) 1.文章:modbus4j串口通讯 - u010655348的博客 - CSDN博客.html(https://blog.csdn.net/u010655348/article/details/52665228) 2.包:路径:"...\ZC_IDE\Java_3rd\m

我的Modbus Slave/Client开发历程(Rtu/AscII/Tcp)

我的Modbus Slave/Client开发历程(Rtu/AscII/Tcp) 分类: [自动化]2007-07-19 10:04 34038人阅读 评论(38) 收藏 举报 vb嵌入式dostcp语言医疗 其实很早就想写写关于Modbus的开发历程,但牵扯项目较多,不同语言版本较多,头绪繁杂,一时不知从何写起.最近的医疗项目的通信部分,重新调整为Modbus协议,并且内容几乎涵盖了Modbus的方方面面(Rtu/Tcp,Slave/Client相关开发),所以更坚定了写Modbus信心,今天

C# 开发Modbus Rtu客户端 modbus测试Demo,Modbus 串口通信 , 虚拟MODBUS-RTU测试

前言 本文将使用一个NuGet公开的组件技术来实现一个ModBus RTU的客户端,方便的对Modbus rtu的服务器进行读写,这个服务器可以是电脑端C#设计的,也可以是PLC实现的,也可以是其他任何支持这个通信协议的服务器. github地址:https://github.com/dathlin/HslCommunication 如果喜欢可以star或是fork,还可以打赏支持. 在Visual Studio 中的NuGet管理器中可以下载安装,也可以直接在NuGet控制台输入下面的指令安装

Modbus测试工具ModbusPoll与Modbus Slave使用方法

一.介绍 Modbus Poll :Modbus主机仿真器,用于测试和调试Modbus从设备.该软件支持ModbusRTU.ASCII.TCP/IP.用来帮助开发人员测试Modbus从设备,或者其它Modbus协议的测试和仿真.它支持多文档接口,即,可以同时监视多个从设备/数据域.每个窗口简单地设定从设备ID,功能,地址,大小和轮询间隔.你可以从任意一个窗口读写寄存器和线圈.如果你想改变一个单独的寄存器,简单地双击这个值即可.或者你可以改变多个寄存器/线圈值.提供数据的多种格式方式,比如浮点.双

测试Linux下tcp最大连接数限制

现在做服务器开发不加上高并发根本没脸出门,所以为了以后吹水被别人怼“天天提高并发,你自己实现的最高并发是多少”的时候能义正言辞的怼回去,趁着元旦在家没事决定自己写个demo搞一搞. 这个测试主要是想搞明白Linux下哪些参数配置限制了连接数的最大值,上限是多少. 一.先说下demo的思路: 服务端用epoll实现,就是简简单单的接收连接,然后客户端用go的goroutine,每个goroutine就是简单的建立连接,然后什么也不做. 上代码: server: 1 /* 2 * g++ -o te

Modbus tcp 格式说明 通讯机制 附C#测试工具用于学习,测试

前言: 之前的博客介绍了如何用C#来读写modbus tcp服务器的数据,文章:http://www.cnblogs.com/dathlin/p/7885368.html 当然也有如何创建一个服务器文章:http://www.cnblogs.com/dathlin/p/7782315.html 但是上面的两篇文章是已经封装好的API,只要调用就可以实现功能了,对于想了解modbus tcp的原理的人可能就不适合了,最近有不少网友的想要了解这个协议,所以在这里再写一篇介绍Modbus tcp的文章

组态王MODBUS TCP数据报格式

在大家通读Modbus协议时,总是会碰到一些容易混淆的名词,从而导致对于协议的解读出现问题,在本文中,我 们对于Modbus协议中可能会给大家造成困惑的名词作相关的解释. 1.功能码:功能码在modbus协议用于表示信息帧的功能,常用的功能码有03,04,06,16等,其中03功能码的作 用是读保持寄存器内容,04功能码的作用是读输入寄存器内容(输入寄存器和保持寄存器的区别看下文),06功 能码的内容是预置单个保持寄存器,16功能码的内容则是预置多个保持寄存器. 2.输入寄存器和保持寄存器:04

简单测试nginx1.90做TCP协议负载均衡的功能

最近工作中需要做TCP层面的负载均衡,以前网站用的反向代理nginx只支持应用层的负载均衡,对于TCP协议是无能为力的,需要使用LVS(linux虚拟服务器). LVS的特点是高性能和极复杂的配置.对网络环境的要求比较高.最近苦于LVS的配置测试,网上的文档和社区都比较少,按照各种教程配置,TCP报文均无法连通,再往下深究就要去研究公司虚机的网络结构了... 在寻找LVS配置调试方法时,看到一篇最近的文章讲4月28日刚刚发布的nginx1.90,添加了支持TCP协议的负载均衡的,如果只是需要做T

智能家居填坑003 Modbus设备接入篇

Modbus设备 格控TCP系列507E.508M.508D 1.IO端口多:508D有32个DI口.508M有24个DO口.507E有8个DI和8个DO口. 2.原生支持有线Modbus-TCP协议. 3.价格便宜,差评少. 4.支持二次开发:后期计划将普通设备逻辑写入里面,就可以脱离服务器. 5.产品相关资料 :格控资料 准备 格控设备在说明书里详细的说明了设备的设置方式,在此就不多加叙述(不同品牌的设置方式存在差异,均需详细参考说明书). 1.给设备分配与你所在网段匹配的ip地址. eg.