GithubHelp home page GithubHelp logo

mangoautomation / modbus4j Goto Github PK

View Code? Open in Web Editor NEW
846.0 846.0 365.0 6.72 MB

A high-performance and ease-of-use implementation of the Modbus protocol written in Java. Supports ASCII, RTU, TCP, and UDP transports as slave or master, automatic request partitioning and response data type parsing.

License: GNU General Public License v3.0

Java 100.00%

modbus4j's People

Contributors

benji811124 avatar colbycocking avatar industrialcommunication avatar jazdw avatar joelhaggar avatar juancarlosgl avatar mlohbihler avatar natami avatar puckfist avatar radixiotbot avatar terrypacker avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

modbus4j's Issues

Send an instruction every 5 seconds to read the data, after a period of time, IO error

Send an instruction every 5 seconds to read the data, after a period of time, IO error

java.io.IOException: I/O error
 W/System.err:     at java.io.FileInputStream.available0(Native Method)
 W/System.err:     at java.io.FileInputStream.available(FileInputStream.java:323)
 W/System.err:     at java.io.BufferedInputStream.available(BufferedInputStream.java:399)
 W/System.err:     at com.serotonin.modbus4j.sero.messaging.InputStreamListener.run(InputStreamListener.java:91)
 W/System.err:     at java.lang.Thread.run(Thread.java:761)

Write holding register MSB/LSB only

If you are using holding register and ONE_BYTE_INT_UNSIGNED_LOWER / ONE_BYTE_INT_UNSIGNED_UPPER the result of write function is 0x00** or 0x**00.

NPE for trying to read data from slave ID 0

The stack trace looks like this:

ERROR 2019-09-13T15:49:31,219 (com.serotonin.m2m2.util.timeout.TimeoutTask.run:61) - Uncaught Task Exception 
java.lang.NullPointerException: null
	at com.serotonin.modbus4j.ModbusMaster.sendFunctionGroup(ModbusMaster.java:512) ~[?:?]
	at com.serotonin.modbus4j.ModbusMaster.send(ModbusMaster.java:430) ~[?:?]
	at com.serotonin.m2m2.modbus.rt.ModbusDataSourceRT.doPoll(ModbusDataSourceRT.java:187) ~[?:?]
	at com.serotonin.m2m2.rt.dataSource.PollingDataSource.doPollNoSync(PollingDataSource.java:228) ~[mango-3.6.4.jar:?]
	at com.serotonin.m2m2.rt.dataSource.PollingDataSource.scheduleTimeoutImpl(PollingDataSource.java:183) ~[mango-3.6.4.jar:?]
	at com.serotonin.m2m2.rt.dataSource.PollingDataSource$1.scheduleTimeout(PollingDataSource.java:85) ~[mango-3.6.4.jar:?]
	at com.serotonin.m2m2.util.timeout.TimeoutTask.run(TimeoutTask.java:59) ~[mango-3.6.4.jar:?]
	at com.serotonin.timer.Task.runTask(Task.java:179) ~[mango-3.6.4.jar:?]
	at com.serotonin.timer.TaskWrapper.run(TaskWrapper.java:23) ~[mango-3.6.4.jar:?]
	at com.serotonin.timer.OrderedThreadPoolExecutor$OrderedTaskCollection.run(OrderedThreadPoolExecutor.java:336) ~[mango-3.6.4.jar:?]
	at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149) ~[?:1.8.0_172]
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624) ~[?:1.8.0_172]
	at java.lang.Thread.run(Thread.java:748) [?:1.8.0_172]

It's possible this is more a validation bug in Mango due to allowing something to be a modbus IP point with slave ID 0 but not restricting its write type to write only.

How to write multi values that are not continuous in one request?

I want to write multiple values( not continuous ) to one modbus slave. For example, I want to write 1 to offset 1, 2 to offset 5, 3 to offset 10. In order to do this, I can only send three requests. But doing this is much slower than sending one request, especially when there are a lot of offsets to be written. Is there any way to write multi values that are not continuous in just one request?

Or is there any other way to fulfill this requirement(write multi values that are not continuous quickly) ?

发送读写保持寄存器时会出现 Connection reset by peer: socket write error 。再次发送却成功了

public static ModbusFactory modbusFactory = new ModbusFactory();

/**
 * 获取tcpMaster
 */
public static ModbusMaster getMaster() throws Exception {
    IpParameters params = new IpParameters();
    params.setHost("192.168.100.66");
    params.setPort(502);
    params.setEncapsulated(false);

    ModbusMaster tcpMaster = modbusFactory.createTcpMaster(params, false);
    tcpMaster.setTimeout(500);
    tcpMaster.setRetries(3);
    tcpMaster.init();
    return tcpMaster;
}

public static void readHoldingRegister(int slaveId, int offset, int dataType) throws Exception {
BaseLocator locator = BaseLocator.holdingRegister(slaveId, offset, dataType);
Number value = getMaster().getValue(locator);
System.out.println("HoldingRegister寄存器第" + offset + "位数据为:" + value);
}

The doPartition method works incorrectly based on wrong assumption that register ranges doesn't have gaps

To Reproduce
Steps to reproduce the behavior:

  1. Use the following data offsets with RegisterRange.HOLDING_REGISTER
    private int initDataOffsets[]= {
            0x0710, // device name
            0x0711, // device name
            0x0712, // device name
            0x0780, // loads count
            0x1200, // phases num
    };
  1. Create batch read request
BatchRead<Integer> batch = new BatchRead<Integer>();
for (int i= 0; i < initDataOffsets.length; i++) {
    batch.addLocator(i, new ModbusLocator(16, RegisterRange.HOLDING_REGISTER, initDataOffsets[i],
DataType.TWO_BYTE_INT_UNSIGNED, (byte) 0));
}
  1. Try to poll device:
BatchResults<Integer> res= batchRead(master, batch);
  1. If device doesn't have registers between 0x0712 and 0x0780 defined, there will be an error and res will be null.

Expected behavior
List<ReadFunctionGroup<K>> functionGroups must be 3 here. But has 2.

how can i modify nextTransactionId property in TcpMatser class?

在我的项目中需要修改nextTransactionId的值,但是我查看源码之后发现不能修改,如果要让nextTransactionId值变化的话的需要不断去调用getNextTransactionId(),才能让其数值变化,在modbus4j的源码中是不是应该让开发者可以自己设置nextTransactionId的值?

Problem import repository

Hi,
I'm following the readMe.txt file informations and I'm trying to import the modbus4j dependecies in pom.xml file, but I have some problems with the repository. I use Intellij and this is the issue: "transfer for nexus-maven-repository-index.properties failed"

Often happening ModbusTransportException

I can successfully get the data, but meanwhile I am getting many of ModbusTransportException: Unsupported IP protocol id.
Have no idea what to do with it.

Checked the dump from Wireshark. The device answers properly in short time (about 0.5ms).
Seems MessageControl or InputStreamListener screwed up in some way.

Network reconnection does not yield data

When the network is disconnected, data cannot be re connected and data can not be obtained after reconnection ,so i find one bug , change TcpMaster class is ok !

here !

try {
LOG.debug("Modbus4J: Keep-alive connection may have been reset. Attempting to re-open.");
openConnection();
ipResponse = (IpMessageResponse) conn.send(ipRequest);
if (ipResponse == null)
return null;
if(LOG.isDebugEnabled()){
StringBuilder sb = new StringBuilder();
for (byte b : Arrays.copyOfRange(ipResponse.getMessageData(),0,ipResponse.getMessageData().length)) {
sb.append(String.format("%02X ", b));
}
LOG.debug("Response: " + sb.toString());
}
return ipResponse.getModbusResponse();
}
catch (Exception e2) {
// ====================add one line code is ok ===================
closeConnection();
LOG.debug("Exception: " + e2.getMessage() + " " + e2.getLocalizedMessage());
throw new ModbusTransportException(e2, request.getSlaveId());
}

how

now,i will read a Electric energy monitor 30function code's data,how to use modbus4j

Serial port connection

Hi!

I have some trouble with ModbusSerialMaster. I got a NPE during reading registers.

My code:

`

    SerialParameters parameters = new SerialParameters();

    parameters.setPortName("/dev/ttyUSB1");
    parameters.setBaudRate(9600);
    parameters.setDatabits(8);
    parameters.setStopbits(1);
    parameters.setParity("none");
    parameters.setEncoding("rtu");
    parameters.setEcho(false);

    ModbusSerialMaster master = new ModbusSerialMaster(parameters);

    master.connect();
    master.readMultipleRegisters(1, 0, 100);
    master.disconnect();

`
And stack:

Exception in thread "main" java.lang.NullPointerException at com.ghgande.j2mod.modbus.net.SerialConnection.setComPortTimeouts(SerialConnection.java:221) at com.ghgande.j2mod.modbus.io.ModbusSerialTransport.setTimeout(ModbusSerialTransport.java:142) at com.ghgande.j2mod.modbus.io.ModbusSerialTransport.open(ModbusSerialTransport.java:131) at com.ghgande.j2mod.modbus.io.ModbusSerialTransport.writeMessage(ModbusSerialTransport.java:73) at com.ghgande.j2mod.modbus.io.ModbusSerialTransaction.execute(ModbusSerialTransaction.java:143) at com.ghgande.j2mod.modbus.facade.AbstractModbusMaster.readMultipleRegisters(AbstractModbusMaster.java:236)

Library version: 2.3.1

Missing dependency

Hi

I have downloaded the library.

I tried to compile the project but the build failed

An error has occurred while processing the Maven artifact tasks.
[mvn:dependencies] Diagnosis:
[mvn:dependencies]
[mvn:dependencies] Unable to resolve artifact: Missing:
[mvn:dependencies] ----------
[mvn:dependencies] 1) com.serotonin:serotonin-utils:jar:2.1.6
[mvn:dependencies]
[mvn:dependencies] Try downloading the file manually from the project website.
[mvn:dependencies]
[mvn:dependencies] Then, install it using the command:
[mvn:dependencies] mvn install:install-file -DgroupId=com.serotonin -DartifactId=serotonin-utils -Dversion=2.1.6 -Dpackaging=jar -Dfile=/path/to/file
[mvn:dependencies]
[mvn:dependencies] Alternatively, if you host your own repository you can deploy the file there:
[mvn:dependencies] mvn deploy:deploy-file -DgroupId=com.serotonin -DartifactId=serotonin-utils -Dversion=2.1.6 -Dpackaging=jar -Dfile=/path/to/file -Durl=[url] -DrepositoryId=[id]
[mvn:dependencies]
[mvn:dependencies] Path to dependency:
[mvn:dependencies] 1) com.infiniteautomation:modbus4j:jar:2.0.6
[mvn:dependencies] 2) com.serotonin:serotonin-utils:jar:2.1.6

Into the modbus4j-maven-local, the last version available is the 2.1.4
I changed the version in pom.xml, but some classes are missing

  • EpollStreamTransportCharSpaced
  • StreamTransportCharSpaced

Could you add the latest version to modbus4j-maven-local?

Regards

Daniele

How to modify the default timeout when using the Modbus RTU Master?

I have a remote equipement to be communicated with the Modbus RTU protocol. I use the Netty framework deal with the TCP/IP layer, writting a wrapper of SerialPort by the Netty, I did it. But when I test my case, I found modbus4j sometimes send a request twice, I checked the source code, found the timeout is set to 500 default.Sometimes 500ms is too short for the TCP/IP communication. So I set the RtuMaster timeout to 3000ms, unfortunately, it does't work. I found the timeout parameter is useless for the Modbus RTU Master, the valid one in the MessageControl class. So how to change the default timeout value in the MessageControl? I can‘t’ find a way achieve it.

run modbus4j error

I’m importing modbus 4j-2.0.2. Jar and JSSC-2.8.0. Jar, error running project as follows:

java.lang.NoSuchMethodError: com.serotonin.io.serial.SerialUtils.openSerialPort
at com.serotonin.modbus4j.serial.SerialMaster.init(SerialMaster.java:58)
at com.serotonin.modbus4j.serial.rtu.RtuMaster.init(RtuMaster.java:45)

I need a solution,thank your!

Serial Modbus RTU

Can you give an example for Modbus rtu serial that read from a holding register. And Is there any forums to discuss about this libraries ?

Should we need a MessageControlListener?

You konw, usually we need to record the content of sent and received. Now we had DEBUG that log control variables in MessageControl, but it is inconvenient for use ,so it may be more useful to add a listener to MessageControl.

Hope this suggestion can be adopted :)

Floating Point Number is Not Accurate in modbusTcp

Hello, recently I use lots of the read and write FOUR_BYTE_FLOAT function(batchRead) in your MODBUS TCP module, I found the number is not accurate(maybe my own problem). More specific, the float numbers generally have an error of 0.5%, which is not normal for floating point numbers.

I am guessing, is it possible that the 3rd and 4th bytes are flipped that causes this problem?

Does anyone else has this problem?

modbus tcp writeHoldingRegister offset over nine will occur exception

I use modbus4j to create a tcp modbus slave, and want to write some datas into HoldingRegister, I use
/* com.serotonin.modbus4j.code.DataType
public static void writeHoldingRegister(int slaveId, int offset, Number value, int dataType)
throws ModbusTransportException, ErrorResponseException, ModbusInitException {
// 类型
BaseLocator locator = BaseLocator.holdingRegister(slaveId, offset, dataType);
tcpMaster.setValue(locator, value);
}*/

to write some float data, 1 float =2 registers=4 bytes , when the offset greater than nine, will occur exception,data cant not write into HoldingRegister,and response 01 90 02 CD C1,debug logs like below:

[17:46:55:113] [DEBUG] - com.serotonin.modbus4j.ip.tcp.TcpMaster.sendImpl(TcpMaster.java:156) - Response: 01 06 00 08 00 22 88 11
[17:46:55:115] [DEBUG] - com.serotonin.modbus4j.ip.tcp.TcpMaster.sendImpl(TcpMaster.java:137) - Encap Request: 01 10 00 09 00 02 04 42 3C 00 00 E7 B1
[17:46:55:115] [DEBUG] - com.serotonin.modbus4j.ip.tcp.TcpMaster.sendImpl(TcpMaster.java:142) - Sending on port: 502
HoldRrgister at 9 was set from 16956 to 16956

I don,t know why ,need help.

socket connection is lost

com.serotonin.modbus4j.exception.ModbusTransportException: java.net.SocketException: Software caused connection abort: socket write error
at com.serotonin.modbus4j.ip.tcp.TcpMaster.sendImpl(TcpMaster.java:183)
at com.serotonin.modbus4j.ModbusMaster.send(ModbusMaster.java:105)

创建 createTcpListener 如何让多个从站跟你建立连接

public ModbusTCPClient(String host, int port) throws ModbusInitException {
    IpParameters params = new IpParameters();
    params.setHost(host);
    params.setPort(port);
    params.setEncapsulated(false);
    this.rtuMaster = modbusFactory.createTcpListener(params);
    //设置超时时间
    this.rtuMaster.setTimeout(2000);
    //设置重连次数
    this.rtuMaster.setRetries(3);
    //初始化
    this.rtuMaster.init();
}

Plan to support extended (two bytes) slave addressing?

How does 2-byte slave addressing work?

Since a single byte is normally used to define the slave address and each slave on a network requires a unique address, the number of slaves on a network is limited to 256. The limit defined in the modbus specification is even lower at 247. To get beyond this limit, a modification can be made to the protocol to use two bytes for the address. The master and the slaves would all be required to support this modification. Two byte addressing extends the limit on the number of slaves in a network to 65535. By default, the Simply Modbus software uses 1 byte addressing. When an address greater than 255 is entered, the software automatically switches to 2 byte addressing and stays in this mode for all addresses until the 2 byte addressing is manually turned off.

"Illegal function" response when read/write coils

It returns "Illegal function" when I read or write coils.
Version: 3.0.5
Code:

    public static void main(String[] args) {
        IpParameters ipParameters = new IpParameters();
        ipParameters.setHost("192.168.31.200");
        ipParameters.setPort(502);

        ModbusFactory modbusFactory = new ModbusFactory();
        ModbusMaster master = modbusFactory.createTcpMaster(ipParameters, false);
        int slaveId = 1;
        try {
            master.init();
            readCoilTest(master, slaveId, 0, 1);
        } catch (ModbusInitException e) {
            e.printStackTrace();
        }
    }

    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(Arrays.toString(response.getBooleanData()));
            }
        } catch (ModbusTransportException e) {
            e.printStackTrace();
        }
    }

Logs:

10:58:15.121 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Encap Request: 00 01 00 00 00 06 01 01 00 00 00 01 
10:58:15.137 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Sending on port: 502
10:58:15.219 [main] DEBUG com.serotonin.modbus4j.ip.tcp.TcpMaster - Response: 00 01 00 00 00 03 01 81 01 
Exception response: message=Illegal function

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.