Java MODBUS RTU主代码示例代码

时间:2014-10-29 01:17:12

标签: java serial-port rxtx modbus

我需要用Java编写支持03 - Read Holding Registers16 - Write Multiple Registers的Modbus RTU主应用程序。

我找到了三个java库:jamodj2modmodbus4j。我尝试了所有这些库(我花了大约4个小时)但它仍然无效。

您是否知道任何分步教程或示例代码?

我正在使用USB-> RS-485转换器。如果我在QModBus中测试,它运行良好。

谢谢。

import java.io.File;
import com.serotonin.io.serial.SerialParameters;
import com.serotonin.modbus4j.ModbusFactory;
import com.serotonin.modbus4j.ModbusMaster;
import com.serotonin.modbus4j.code.DataType;
import com.serotonin.modbus4j.code.RegisterRange;
import com.serotonin.modbus4j.exception.ModbusInitException;

public class Modbus4JTest {

   public static void main(String[] args) throws Exception {  
        ModbusFactory factory = new ModbusFactory();
        SerialParameters params = new SerialParameters();
          params.setCommPortId("/dev/ttyUSB1");
          params.setBaudRate(9600);
          params.setDataBits(8);
          params.setStopBits(1);
          params.setParity(0);
        ModbusMaster master = factory.createRtuMaster(params);
        master.setTimeout(2000);
        master.setRetries(0);
        long start = System.currentTimeMillis();

        // Don't start if the RTU master can't be initialized.
        try {
            master.init();
        } catch (ModbusInitException e) {
          System.out.println( "Modbus Master Init Error: " + e.getMessage());
          return;
        }


        try {
            System.out.println("Reg. 1001 Value:" + master.getValue(7, RegisterRange.HOLDING_REGISTER, 1000, DataType.FOUR_BYTE_FLOAT_SWAPPED));

            // more like the above until all required register values are read.
            // ..
        }
        finally {
            master.destroy();
        }

        System.out.println("Time elapsed: " + (System.currentTimeMillis() - start) + "ms");
  }
}

import java.io.File;

import com.ghgande.j2mod.modbus.ModbusCoupler;
import com.ghgande.j2mod.modbus.io.ModbusSerialTransaction;
import com.ghgande.j2mod.modbus.msg.ModbusRequest;
import com.ghgande.j2mod.modbus.msg.ReadInputRegistersRequest;
import com.ghgande.j2mod.modbus.msg.ReadInputRegistersResponse;
import com.ghgande.j2mod.modbus.net.SerialConnection;
import com.ghgande.j2mod.modbus.util.SerialParameters;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersResponse;

// -Djava.library.path="/usr/lib/jni/"
public class J2mod {
    public static void main(String[] args) throws Exception {
        File lock = new File("/var/lock/LCK..ttyUSB0"); 
        lock.delete();
        File lock1 = new File("/var/lock/LCK..ttyUSB1"); 
        lock1.delete();

        SerialConnection con = null; // the connection
        ModbusSerialTransaction trans = null; // the transaction
        //ReadInputRegistersRequest req = null; // the request
        ReadHoldingRegistersRequest req = null;
        ReadHoldingRegistersResponse res = null;
        //ReadInputRegistersResponse res = null; // the response
        String portname = null; // the name of the serial port to be used

        int unitid = 0; // the unit identifier we will be talking to
        int ref = 0; // the reference, where to start reading from
        int count = 0; // the count of IR's to read
        int repeat = 1; // a loop for repeating the transaction
        try {
            portname = "/dev/ttyUSB1";
            //System.setProperty("gnu.io.rxtx.SerialPorts", portname);
            unitid = 2;
            ref = 0;
            count = 4;
        } catch (Exception ex) {
            ex.printStackTrace();
            System.exit(1);
        }
        // 2. Set master identifier
        // ModbusCoupler.createModbusCoupler(null);
        ModbusCoupler.getReference().setUnitID(1);
        // 3. Setup serial parameters
        SerialParameters params = new SerialParameters();
        params.setPortName(portname);
        params.setBaudRate(9600);
        params.setDatabits(8);
        params.setParity("None");
        params.setStopbits(1);
        params.setEncoding("rtu");
        params.setEcho(false);
        // 4. Open the connection
        con = new SerialConnection(params);
        con.open();
        // 5. Prepare a request
        req = new ReadHoldingRegistersRequest(unitid, ref, count);
        //req = new ReadInputRegistersRequest(ref, count);
        //req.setUnitID(unitid);
        //req.setHeadless();
        // 6. Prepare a transaction
        trans = new ModbusSerialTransaction(con);
        trans.setRequest(req);
        int k = 0;
        do {
            trans.execute();
            res = (ReadInputRegistersResponse) trans.getResponse();
            //res = (ReadHoldingRegistersResponse) trans.getResponse();
            for (int n = 0; n < res.getWordCount(); n++) {
                System.out.println("Word " + n + "=" + res.getRegisterValue(n));
            }
            k++;
        } while (k < repeat);
        // 8. Close the connection
        con.close();
    }
}

0 个答案:

没有答案