Coder Social home page Coder Social logo

kochedykov / jlibmodbus Goto Github PK

View Code? Open in Web Editor NEW
285.0 32.0 127.0 2.24 MB

JLibModbus - is an implementation of the Modbus protocol v1.1b in java language. Java modbus library. It works. Welcome.

Home Page: http://kochedykov.github.io/jlibmodbus/

License: Apache License 2.0

Java 100.00%
java modbus modbus-tcp modbus-rtu modbus-master modbus-slave rxtx jssc libmodbus jserialcomm

jlibmodbus's Introduction

README

The MODBUS protocol implementation in pure java.

The main advantages of the library are following:
- the library supports a lot of communication libraries (jssc, rxtx, purejavacomm, java comm api); 
- the library has (practically) complete implementation of the modbus protocol v1.1b.

AUTHORS

Vladislav Y. Kochedykov, software engineer, technical expert.

CONTACT

If you have problems, questions or suggestions, please contact me at email address [email protected]

To learn how to use the library you can either use examples in "examples\com\invertor\examples\modbus" folder or contact me at email.

Maven dependency:

The latest stable release.
<dependency>
  <groupId>com.intelligt.modbus</groupId>
  <artifactId>jlibmodbus</artifactId>
  <version>1.2.9.9</version>
</dependency>

WEB SITE

project homepage:
http://jlibmodbus.sourceforge.net
https://github.com/kochedykov/jlibmodbus

purejavacomm homepage:
http://www.sparetimelabs.com/purejavacomm/purejavacomm.php
https://github.com/nyholku/purejavacomm

jssc home page:
https://code.google.com/p/java-simple-serial-connector
https://github.com/scream3r/java-simple-serial-connector

rxtx home page:
http://users.frii.com/jarvi/rxtx/index.html

jserialcomm homepage:
https://github.com/Fazecast/jSerialComm

-----------------------------------------------------------------------------------------------------------
----Release version 1.2.9.9 -------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS
	* The release contains a bug fix that do rollback changes by commit 010c95917c913c355bd9599cc2458094a311da2b
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.9.8 -------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS
	* The release contains several bug fixes and the latest pull requests including some new features 
	* (see git log on github https://github.com/kochedykov/jlibmodbus).
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.9.7 -------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS
	* The automatic serial port connector selection is rolled back.
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.9.6 -------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS
	* IMPORTANTLY! Fixed the issue #22: MODBUS Master TCP - Socket left open.
	* Fixed a bug with listening for incoming data on Android Things device.
	* Add automatic selection of a serial port connector.
	* Add Android Things support.
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.9.5 -------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* Fixed a bug with an incorrect conversion from two integers to a long value.
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.9.4 -------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* Fixed incoming frame logging.
	* Fixed a bug in OutputStreamASCII - add unimplemented method write(byte[], int, int).
	* Fixed the issue #17: Incorrect logic if lrc equals zero. Thanks to https://github.com/mlasevich
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.9.3 -------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* Fixed hasNext() in ModbusValues iterator.
	* Fixed error in JSerialComm implementation. https://sourceforge.net/p/jlibmodbus/bugs/2/
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.9.2 -------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* Fixed a bug with setting timeout in SerialPortLoopback.
	* Fixed a bug with setting a slave timeout.
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.9.1 -------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS
	* Experimental! Implemented RTU over TCP. Add a new serial port factories TcpClient and TcpServer. Usage: //server side SerialUtils.setSerialPortFactory(new SerialPortFactoryTcpServer(tcpParameters)); ModbusSlave slave = ModbusSlaveFactory.createModbusSlaveRTU(serialParameters);
	* IMPORTANTLY! Fixed the issue #15: Bug in setRange method. Thanks to https://github.com/shdk
	* Added ModbusSlaveSerialObserver and SerialPortInfo classes to notify if the com port was opened or closed.
	* IMPORTANTLY! Added the jSerialComm library support.
	* IMPORTANTLY! Fixed the issue #14:Bug in DataHolder class. Thanks to https://github.com/shdk
	* Added API to retrieve information about a TCP client connected to the TCP slave.
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.9.0 -------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS
	* IMPORTANTLY! Renamed package from com.invertor.modbus to com.intelligt.modbus.jlibmodbus! 
	* IMPORTANTLY! Change default read timeout to 1000 ms.
	* Fixed a bug in GetCommEventLog.
	* Added data frame events to Input/Output streams.
	* Added the loopback serial port for testing applications without actual serial hardware. Author Kevin Kieffer.
	* Added method ReadCoilsResponse#getModbusCoils that returns a ModbusCoils instance.
	* Fixed a bug in ModbusValue#next().
	* Fixed errors in data conversion operations.
	* Added method ReadHoldingRegisters#getHoldingRegisters that returns a ModbusHoldingRegisters instance.
	* Renamed getBytes -> getBytesBe.
	* Renamed Coils->ModbusCoils, HoldingRegistors->ModbusHoldingRegisters.
	* Added class ModbusValues.
	* Renamed getValues -> getBytes, setValues -> setBytes.
	* Added additional helpers.
	* Added the BroadcastResponse class to avoid timeout exception while sending broadcast requests.
	* Fixed an incorrect logic if crc equals zero. Thanks to flooduk (https://github.com/flooduk).
	* Fixed handling of broadcast requests.
	* Fixed handling of RestartCommunicationsOption.
	* Optimized memory usage.
	* Fixed the MIN_PDU_LENGTH value.
	* Reduced copy operations number.
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.8.4 -------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS
	* Added basic maven pom file
	* Thread safety. Thanks to Kevin Kieffer.
	* HoldingRegisters and Coils is now observable. Thanks to Kevin Kieffer.
	* Added a method to get a byte-buffer from ReadHoldingRegistersResponse.
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.8.3 -------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS
	* IMPORTANTLY! Fixed bug #1 Support of SlaveID=255 with ModbusTCP. Thanks to Francois DELOYE (https://sourceforge.net/u/sesa258801).
	* Added broadcast support.
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.8.2 -------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS
	* Added a new method - SerialUtils#getConnectorVersion.
	* Fixed bug in ModbusMaster#disconnectImpl. Thanks to dpozimski (https://github.com/dpozimski)!
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.8.1 -------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS
	* Fixed bug: setting of the "connected" status had no effect.
	* Added ModbuMaster#connectImpl and ModbusMaster#disconnectImpl methods.
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.8 ---------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS
	* Added a new method ModbusMaster#isConnected that returns true if a master is connected to a remote slave.
	* Added a new method ModbusSlave#isListening method that returns true if a slave is already listening for incoming connections.
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.7 ---------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS
	* IMPORTANTLY! Fixed bug with reading of multiple values in a request.
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.6 ---------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS
	* Fixed bug with a NPE thrown if setReadTimeout is invoked before port is opened.
	* IMPORTANTLY! Added the PureJavaComm library support.
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.5 ---------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS
	* Added readTimeout to ModbusSlave. 
	* API changes: Deleted a few factory-methods from ModbusMasterFactory and ModbusSlaveFactory.
	* API changes: Renamed ModbusEvent to ModbusCommEvent.
	* API changes: Added methods Coils#quantity() and HoldingRegisters#quantity().
	* API changes: ModbusSlaver#open() -> ModbusSlaver#listen(), ModbusSlaver#close() -> ModbusSlaver#shutdown().
	* API changes: ModbusMaster#open() -> ModbusMaster#connect(), ModbusMaster#close() -> ModbusMaster#disconnect().
	* Fixed bug that type of quantity must be double or float before it'll be divided.
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.4 ---------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS
	* Fixed bug with address and quantity checking in ReadCoilsRequest#checkAddressRange.
	* Improved search of a ModbusFunctionCode instance by value.
	* Fixed issues found by FindBug utility(http://findbugs.sourceforge.net).
	* Fixed bug with SerialPortJSSC#read(byte[] b, int off, int len) method.
	* Fixed bug with setting readTimeout before opening a connection.
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.3 ---------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS
	* Added a class to obtain the version of the library.
	* Improved logger output.
	* Added method getPortIdentifiers to get a list of available port identifiers.
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.2 ---------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS
	* IMPORTANTLY! Added support for java communication api 3.0.
	* IMPORTANTLY! Migrated to the apache license version 2.0.
	* Methods "purgeRx", "purgeTx", "clear" are removed from SerialPort class.
	* Method "reset" is removed from ModbusConnection.
	* Fixed potential bug with infinite loop in ModbusMaster.readResponse.
	* Added method ModbusConnection.getReadTimeout.
	* Prevents a NullPointerException if master is used before it has been opened.
-----------------------------------------------------------------------------------------------------------
----Release version 1.2.1 ---------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS:
	* IMPORTANTLY! Add the RXTX library support! Usage: SerialUtils.setSerialPortFactory(new SerialPortFactoryRXTX());
	* Added checking if jssc library is available.
	* Fixed potential bug with reading of byte array.
	* Added avoiding some NPEs.
	* IMPORTANTLY! Fixed bug with flushing of output buffers.
	* Modbus RTU master is now able to connect via tcp socket (in case of rs232/rs485 to wifi adapters).
-----------------------------------------------------------------------------------------------------------
----Release version 1.2 -----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS:
	* Added extended logging.
	* Add auto-increment of transaction id. See Modbus.setAutoIncrementTransactionId.
-----------------------------------------------------------------------------------------------------------
----Release version 1.1 -----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* NEWS:
	* IMPORTANTLY! Fixed bug with offset reading.
	* IMPORTANTLY! Fixed data conversion issues.
-----------------------------------------------------------------------------------------------------------
----Release version 1.0 -----------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------
	* Implemented MODBUS functions:
	* 0x01 - Read Coils
	* 0x02 - Read Discrete Inputs
	* 0x03 - Read Holding Registers
	* 0x04 - Read Input Registers
	* 0x05 - Write Single Coil
	* 0x06 - Write Single Register
	* 0x07 - Read Exception Status(serial line only)
	* 0x08 - Diagnostics(serial line only)
	* 0x0B - Get Comm Event Counter(serial line only)
	* 0x0C - Get Comm Event Log(serial line only)
	* 0x0F - Write Multiple Coils
	* 0x10 - Write Multiple Registers
	* 0x11 - Report Slave Id(serial line only)
	* 0x14 - Read File Record
	* 0x15 - Write File Record
	* 0x16 - Mask Write Register
	* 0x17 - Read Write Multiple Registers
	* 0x18 - Read Fifo Queue
	* 0x2B - Encapsulated Interface Tansport(Read Device Identification interface, (0x2B / 0x0E))

jlibmodbus's People

Contributors

670141733 avatar abdelazizsaid250 avatar efendioglu avatar gtbx avatar halimselim avatar kochedykov avatar ktdynamic avatar wielantu avatar wolfgangfahl 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

jlibmodbus's Issues

this gives null pointer exception when i use lib 1.2.9 but it works fine when i use 1.2.8.4,

/*Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
at com.intelligt.modbus.jlibmodbus.serial.SerialUtils.createSerial(SerialUtils.java:63)
at com.intelligt.modbus.jlibmodbus.master.ModbusMasterRTU.(ModbusMasterRTU.java:34)
at com.intelligt.modbus.jlibmodbus.master.ModbusMasterFactory.createModbusMasterRTU(ModbusMasterFactory.java:48)
at powerMeterConnector.PMconnection.(PMconnection.java:43)
*/
public class PMconnection {
private static PMconnection plc;
private ModbusMaster master;

public PMconnection() {
     SerialParameters sp = new SerialParameters();
    //Modbus.setLogLevel(Modbus.LogLevel.LEVEL_DEBUG); reading response
   try {
         
        
        
            String[] port_list =new SerialPortList().getPortNames();
        
        if (port_list.length > 0) {
          //  System.out.println("Port: "+port_list[0]);
            //set the compatible parameters for the PLC
            sp.setDevice(port_list[0]);
            sp.setBaudRate(SerialPort.BaudRate.BAUD_RATE_9600);
            sp.setDataBits(8);
            sp.setParity(SerialPort.Parity.EVEN);
            sp.setStopBits(1);
            //if(master==null){ //singleton (not the correct)
                master = ModbusMasterFactory.createModbusMasterRTU(sp);
          // }
            
        }
    } catch (RuntimeException e) {
        throw e;
    } catch (Exception e) {
        e.printStackTrace();
    }
    


}
public static PMconnection getInstance() {
    if(plc==null){
        plc=new PMconnection();
    }
    return plc;
}
public ModbusMaster getMaster(){
    return master;

}

}

Using library with Bluetooth connection

Hi all, I'm an android developer and I need to connect my app with a remote bluetooth device that use Modbus RTU protocol; application must request some data and display them to a view.

I create a communication socket with the device but I can not understand how use jlibmodbus lib to send a modbus rtu request.

Can anyone help me?

Thanks in advance
Mattia

Android as slave Bind Exception

getting this exception when setting up library on android. on listen() method
java.net.BindException: bind failed: EACCES (Permission denied)

Another thing is that in this lines

   synchronized public void listenImpl() throws ModbusIOException {
       try {
           server = new ServerSocket(tcp.getPort());
           mainThread = new Thread(this);
           setListening(true);
           mainThread.start();
       } catch (IOException e) {
           throw new ModbusIOException(e);
       }
   }

we only pass port to server socket , and not using any other data, it might be that I misunderstood your idea, but can you please explain it a bit, either here or in private message.

ModbusChecksumException: checksum error arise again!

Caused by: com.intelligt.modbus.jlibmodbus.exception.ModbusChecksumException: checksum error: received 59392, calculated 48617
at com.intelligt.modbus.jlibmodbus.net.stream.InputStreamRTU.frameCheck(InputStreamRTU.java:44) ~[jlibmodbus-1.2.9.4.jar!/:?]
at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransportSerial.read(ModbusTransportSerial.java:46) ~[jlibmodbus-1.2.9.4.jar!/:?]
at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransport.readMessage(ModbusTransport.java:69) ~[jlibmodbus-1.2.9.4.jar!/:?]
at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransport.readResponse(ModbusTransport.java:64) ~[jlibmodbus-1.2.9.4.jar!/:?]
at com.intelligt.modbus.jlibmodbus.master.ModbusMaster.readResponse(ModbusMaster.java:111) ~[jlibmodbus-1.2.9.4.jar!/:?]
at com.intelligt.modbus.jlibmodbus.master.ModbusMaster.processRequest(ModbusMaster.java:134) ~[jlibmodbus-1.2.9.4.jar!/:?]
at com.intelligt.modbus.jlibmodbus.master.ModbusMaster.readHoldingRegisters(ModbusMaster.java:193) ~[jlibmodbus-1.2.9.4.jar!/:?]
at com.certusnet.flexedge.modbus.service.ModbusExampleService.readHoldingRegisters(ModbusExampleService.java:65) ~[classes!/:1.0.0]

ModBus Master TCP - Socket left open

Hi,
I'm using your library and I have noticed that the ModbusTransportTCP class do not store each new created socket in any variable and therefore the sockets are never closed!
Analyzing the source code I found the way the socket is constructed and how it is passed to input and output streams. The problem occurs when the ModbusTransportTCP.close() method is invoked: only input and output streams are closed, but the socket is left opened.

At ModbusTransportTCP, row 40, it is possible to notice that the socket is not stored (it is stored in the input and output stream, but in any case it is left opened when the close method is invoked).
At ModbusTransport, row 45, it is possible to see how the close method is propagated only to input and output streams.

This is fine if you use only one connection to do everything but when a connection is opened and closed multiple times (before garbage collectors runs, of course) to the same ModBus endpoint, this situation happens:

bug-jlibmodbus
I debugged my application and I'm sure that the ModbusMaster.disconnect() method is invoked each time, but the connections remains opened, as you can see in the screenshot. When this situation happens, the only solution is to wait that the connections are garbage collected and closed by the operating systems (or restarting your application, of course).

I'm using version 1.2.9.5 with Maven.

If you need more information please don't hesitate to ask.

Wrong implementation at the DataUtils.dwordFromWords

Hello.

Your implementation looks like
public static int dwordFromWords(int l, int h) { return (l & 0xffff) & ((h & 0xffff) << 16); }
There is mistake at the AND operation between l and h at the return statement. I think you should use OR operation.

TCP slave is stuck

I'm building Tomcat application to simulate Slave device. First query works, all data is read by external software (https://www.modbustools.com/), but then external software is stuck. Here are the logs on Slave:

Client connected /127.0.0.1
INFO: Frame recv: 00000000000601030000000A
onReadHoldingRegisterRange: address 0, quantity 10
INFO: Frame sent: 0000000000170103140000006F00DE001501BC00000000000000000026
WARNING: java.net.SocketTimeoutException: Read timed out
Client disconnected /127.0.0.1

If I run parallel instance of external software it is not getting data, logs on Slave:

Client connected /127.0.0.1
WARNING: java.net.SocketTimeoutException: Read timed out
Client disconnected /127.0.0.1

Sometime at that even first external software got one response, but then stuck again.

When trying Disconnect in external software, it freeze and stop responding, so it might be something with network handling.

Code on Slave:

        try {

            ModbusSlaveTCP slave;

            TcpParameters tcpParameters = new TcpParameters();

            tcpParameters.setHost(InetAddress.getLocalHost());
            tcpParameters.setKeepAlive(true);
            tcpParameters.setPort(33000);

            slave = (ModbusSlaveTCP) ModbusSlaveFactory.createModbusSlaveTCP(tcpParameters);
            
            Modbus.setLogLevel(Modbus.LogLevel.LEVEL_VERBOSE);

            MyOwnDataHolder dh = new MyOwnDataHolder();          
            dh.addEventListener(new ModbusEventListener() {
                
                @Override
                public void onReadHoldingRegisterRange(int address, int quantity) {
                    System.out.println("onReadHoldingRegisterRange: address " + address + ", quantity " + quantity);
                }

            });
            
            Observer o = new ModbusSlaveTcpObserver() {
                @Override
                public void clientAccepted(TcpClientInfo info) {
                    System.out.println("Client connected " + info.getTcpParameters().getHost());
                }

                @Override
                public void clientDisconnected(TcpClientInfo info) {
                    System.out.println("Client disconnected " + info.getTcpParameters().getHost());
                }
            };
            slave.addObserver(o);
            
            slave.setDataHolder(dh);
            hr = new ModbusHoldingRegisters(10);
            hr.set(0, 12345);
            hr.set(1, 111);
            slave.getDataHolder().setHoldingRegisters(hr);
            slave.setServerAddress(1);
            
            slave.listen();

        } 
        catch (RuntimeException e) {
            throw e;
        } 
        catch (Exception e) {
            e.printStackTrace();
        }

Terminating external software and run again is not helping.

Best regards,

maven support

Vladislav - your library looks promising. I'd love to use it.
It would be great if it would be "mavenized" and made available on maven central.

"WARNING The POM for jlibmodbus:jar is invalid" when build with maven

Find

[WARNING] The POM for com.intelligt.modbus:jlibmodbus:jar:1.2.9.7 is invalid, transitive dependencies (if any) will not be available, enable debug logging for more details

when building with maven.

Dependency in my pom.xml is

    <dependency>
        <groupId>com.intelligt.modbus</groupId>
        <artifactId>jlibmodbus</artifactId>
        <version>1.2.9.7</version>
    </dependency>

Implements Modbus Function 20(0x14)

It would be great to show in simple Example how we can implements Modbus Function 20(0x14). I do not understand how it is works and always get TimeOutException but ModbusMaster.isConected

WriteSingleCoilRequest.setCoil(true) always fails

It is not possible to send a WriteSingleCoilRequest with value true/ON.

The fix for #33 added a short cast to the value parameter in Modbus.java:

    static public boolean checkRegisterValue(int value) {
        return checkRange((short)value, 0, Modbus.MAX_REGISTER_VALUE);
    }

So

   Modbus.checkRegisterValue(COIL_VALUE_ON); 

always returns false.

This means

WriteSingleCoilRequest.setCoil(true) 

always fails.

jserialcomm 2.0 is not in pom

lib has jserialcomm 2.0.2 but pom has this:

com.fazecast jSerialComm 1.3.11

This causes it to time out if I use 2.x locally.

Hopefully you will update maven with this ๐Ÿ‘

standard and configurable logging?

I'm using your library in a Spring Boot application and when I set your logging level to debug, the messages I get simply get written to the standard output device. Presuming that you were using Java logging (java.util.logging) I added the necessary bridge to my configuration, but it didn't help.

So I'm guessing that you are not using the standard logging facilities. I would suggest that you change this so that it does just use the standard Java logging, allowing those that use it to configure it appropriately.

Add notifications

The slave should have an API to receive notification that a command was processed.

Register value out of range : 65280

Hello I have problem with last version jlibmodbus 1.2.9.7
when I use function x05 WriteSingleRegister
in
public void setValue(int value) throws ModbusNumberException {
if (!Modbus.checkRegisterValue(value)) {
throw new ModbusNumberException("Register value out of range", value);
}
this.value = ((short) value) & 0xffff;
}

I take error Register value out of range : 65280
in method
static public boolean checkRegisterValue(int value) {
return checkRange((short)value, 0, Modbus.MAX_REGISTER_VALUE);
}

And I fix the checkRange(value, 0, Modbus.MAX_REGISTER_VALUE) after that it worked for me
Did this right or not help me?

ModbusMaster.isConnected doesn't reflect connection state

if a connection is intentionally interrupted, the isConnected function doesn't update at all

catch (ModbusIOException e) {
                System.out.println(m.isConnected());
                e.printStackTrace();
}
true
com.intelligt.modbus.jlibmodbus.exception.ModbusIOException: java.net.SocketException: Software caused connection abort: recv failed
	at com.intelligt.modbus.jlibmodbus.tcp.TcpAduHeader.read(TcpAduHeader.java:103)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransportTCP.read(ModbusTransportTCP.java:50)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransport.readMessage(ModbusTransport.java:69)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransport.readResponse(ModbusTransport.java:64)
	at com.intelligt.modbus.jlibmodbus.master.ModbusMaster.readResponse(ModbusMaster.java:111)
	at com.intelligt.modbus.jlibmodbus.master.ModbusMasterTCP.readResponse(ModbusMasterTCP.java:84)
	at com.intelligt.modbus.jlibmodbus.master.ModbusMaster.processRequest(ModbusMaster.java:134)
	at ModbusTest.App.main(App.java:82)
Caused by: java.net.SocketException: Software caused connection abort: recv failed
	at java.net.SocketInputStream.socketRead0(Native Method)
	at java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
	at java.net.SocketInputStream.read(SocketInputStream.java:170)
	at java.net.SocketInputStream.read(SocketInputStream.java:141)
	at java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
	at java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
	at java.io.BufferedInputStream.read(BufferedInputStream.java:345)
	at com.intelligt.modbus.jlibmodbus.net.stream.InputStreamTCP$1.read(InputStreamTCP.java:55)
	at com.intelligt.modbus.jlibmodbus.net.stream.base.LoggingInputStream.read(LoggingInputStream.java:61)
	at com.intelligt.modbus.jlibmodbus.net.stream.base.ModbusInputStream.read(ModbusInputStream.java:50)
	at com.intelligt.modbus.jlibmodbus.tcp.TcpAduHeader.read(TcpAduHeader.java:91)
	... 7 more

Next Release?

There hasn't been a release since 2018 but there are changes on master that fix some bugs. Most notably the pom is broken and the ModbusCoils class doesn't actually return the coils. It looks like both of these issues have been corrected but no release was ever created. Any chance of a new release so these issues get fixed?

bug in setRange method

setRange method in ModbusCoils and ModbusHoldingRegisters classes is not taking into account the offset parameter for setting the range of values.

Should be:

for (int i = 0; i < range.length; i++) {
     set(i+offset, range[i]);
}

ModbusMasterFactory.createModbusMasterRTU raise exeption

Hello,
In Java is not strong :) Experience is no more than six months, so I had to learn Eclipse RCP and write a modbus driver.
I use the link of your library (downloaded fresh jlibmodbus-1.2.9.7.jar from sourceForge) with jssc.
I encountered the problem that when the ModbusMasterFactory.createModbusMasterRTU function is called the nullptr ex is catched
Once (months 4-5 back) used the source code of your library - and this problem was not observed - the port was set correctly and everything worked. And now here I decided to use jar - and catch the ex (it's clear that for so many months the source code has changed, if I do not understand right away - then I'll debug with your updated sourses). Maybe you can tell me where to dig :)

Judging by the changes - added only thread safety.

[SEVERE] - 00:24:12.081 14-07-2018 - [ru.project.core.script.ScriptProcessor.connectMeasure] - java.lang.NullPointerException
at com.intelligt.modbus.jlibmodbus.serial.SerialUtils.createSerial(SerialUtils.java:63)
at com.intelligt.modbus.jlibmodbus.master.ModbusMasterRTU.(ModbusMasterRTU.java:34)
at com.intelligt.modbus.jlibmodbus.master.ModbusMasterFactory.createModbusMasterRTU(ModbusMasterFactory.java:48)
at ru.project.common.modbus.ModbusMasterPool.getModbusMaster(ModbusMasterPool.java:19)
at ru.project.common.modbus.ModbusMasterHelper.(ModbusMasterHelper.java:32)
at ru.project.driver.measure.MeasureDriver.initMeasures(MeasureDriver.java:79)
at ru.project.driver.measure.MeasureDriver.doStart(MeasureDriver.java:218)
at ru.project.core.script.ScriptProcessor.connectMeasure(ScriptProcessor.java:211)
at ru.project.core.script.ScriptProcessor.connectMeasureManually(ScriptProcessor.java:182)
at ru.project.e4.parts.script.ScriptView$ConnectMeasureJob.run(ScriptView.java:878)
at org.eclipse.jface.operation.ModalContext$ModalContextThread.run(ModalContext.java:119)

import java.util.HashMap;
import java.util.Map;

import com.intelligt.modbus.jlibmodbus.master.ModbusMaster;
import com.intelligt.modbus.jlibmodbus.master.ModbusMasterFactory;
import RS232Configuration;

public class ModbusMasterPool {

	private static Map<String, ModbusMaster> modbusPool = new HashMap<String, ModbusMaster>();

	public static ModbusMaster getModbusMaster(RS232Configuration cfg) throws Exception {
		ModbusMaster mm=null;
		try {

			if (!modbusPool.containsKey(cfg.getPort())) {
				mm = ModbusMasterFactory.createModbusMasterRTU(cfg.asSerialParameters());
				modbusPool.put(cfg.getPort(), mm);
			} else {
				mm = modbusPool.get(cfg.getPort());
			}

			if (!mm.isConnected()) {
				mm.setResponseTimeout(cfg.getTimeOut());
				mm.connect();
			}
		} 
		catch (Exception ex) {
			
			throw new Exception("Unable to connect to com port", ex);
		}
		return mm;
	}
	public static void disconnectAll() throws Exception {
		for (String port : modbusPool.keySet())
			if (modbusPool.get(port).isConnected())
				modbusPool.get(port).disconnect();
		modbusPool.clear();
	}

}







import com.intelligt.modbus.jlibmodbus.serial.SerialParameters;
import com.intelligt.modbus.jlibmodbus.serial.SerialPort.Parity;
import com.intelligt.modbus.jlibmodbus.serial.SerialPort.BaudRate;

public class RS232Configuration {
	private String port = "COM3";
	private BaudRate baudrate = BaudRate.BAUD_RATE_9600;
	private Parity parity = Parity.NONE;
	private int dataBits = 8;
	private int stopBits = 1;
	private int timeOut = 100;//

	public String getPort() {
		return port;
	}

	public void setPort(String port) {
		this.port = port;
	}

	public BaudRate getBaudrate() {
		return baudrate;
	}

	public void setBaudrate(BaudRate br) {
		this.baudrate = br;
	}

	public Parity getParity() {
		return parity;
	}

	public void setParity(Parity parity) {
		this.parity = parity;
	}

	public int getDataBits() {
		return dataBits;
	}

	public void setDataBits(int dataBits) {
		this.dataBits = dataBits;
	}

	public int getStopBits() {
		return stopBits;
	}

	public void setStopBits(int stopBits) {
		this.stopBits = stopBits;
	}

	public SerialParameters asSerialParameters() {
		SerialParameters serialParameters = new SerialParameters();
		serialParameters.setDevice(getPort());
		serialParameters.setBaudRate(getBaudrate());
		serialParameters.setParity(getParity());
		serialParameters.setDataBits(getDataBits());
		serialParameters.setStopBits(getStopBits());
		return serialParameters;
	}


	public void setTimeOut(int timeOut) {
		this.timeOut = timeOut;
	}

	public int getTimeOut() {
		// TODO Auto-generated method stub
		return timeOut;
	}
}

Thanks,
perrym

Truncated modbus messages

I have the following configuration:

Modbus poll application running on a Windows machine connected to a Linux embedded device through an usb-serial adapter:

slaveId=10,
serialBaudRate=38400,
serialDataBits=8,
serialParity=EVEN,
serialStopBits=1,
serialPortFactory=JSerialComm,
serialPortId=/dev/ttymxc1,

With Modbus poll (emulating the modbus master) I'm trying to write with the 'write multiple registers' function 123 registers every 10 ms. In the Linux device I'm running a java class that uses jLibModbus v1.2.9.7 library (it will be the modbus slave) and jSerialComm v2.6.2 which reads correctly first 10-20 messages, then I see continuously in log:

INFO: Frame recv: 0000
WARNING: null

I've edited the 'open' method of SerialPortJSerialComm class as following:

public void open() throws SerialPortException {
    SerialParameters sp = getSerialParameters();
    port = com.fazecast.jSerialComm.SerialPort.getCommPort(sp.getDevice());
    port.openPort();
    
    port.setComPortParameters(sp.getBaudRate(), sp.getDataBits(), sp.getStopBits(), sp.getParity().getValue(), true);
    port.setFlowControl(com.fazecast.jSerialComm.SerialPort.FLOW_CONTROL_DISABLED);
    port.setComPortTimeouts(com.fazecast.jSerialComm.SerialPort.TIMEOUT_READ_SEMI_BLOCKING
        | com.fazecast.jSerialComm.SerialPort.TIMEOUT_WRITE_BLOCKING, 0, 0);

    in = port.getInputStream();
    out = port.getOutputStream();
}

I've also tried playing around with different timeouts configuration without any luck.
What could be possible wrong?
Thank you, regards.
Andrea

Non-blocking API

It would be great to implement non-blocking API but keep current API available.

bug in DataHolder class

checkPointer call in readCoilRange method needs to be fixed. coils field should be passed as parameter instead of holdingRegisters

Thread safety

DataHolder should have a thread safe implementation by default.

Unit ID of master PLC connecting to slave

I'm running the slave to capture incoming modbus messages. I need to be able to identify the source of these incoming messages. When I run the slave in debug, I can get the Unit ID of the master from request.serverAddress. The problem is that the request is locked down inside RequestHandlerTCP that is set in ModbusSlaveTCP.run and placed in the slave's treadPool, which is private. Is there another way of differentiating the source of incoming modbus events? I could get the IP inside the ModbusSlaveTcpObserver.clientAccepted, but that doesn't help if there are multiple simultaneous incoming messages from different devices.

core dump when communicate through modbus RTU on windows 10.

When run the app communicate through Modbus RTU on windows 10, it will be core dump. But same program works fine on the windows 7. The following are captured when run the program. Looks like it related to the jssc plugin.

A fatal error has been detected by the Java Runtime Environment:

EXCEPTION_ACCESS_VIOLATION (0xc0000005) at pc=0x000000007110b5db, pid=740, tid=12968

JRE version: Java(TM) SE Runtime Environment (10.0.1+10) (build 10.0.1+10)

Java VM: Java HotSpot(TM) 64-Bit Server VM (10.0.1+10, mixed mode, tiered, compressed oops, g1 gc, windows-amd64)

Problematic frame:

C [jSSC-2.8_x86_64.dll+0xb5db]

No core dump will be written. Minidumps are not enabled by default on client versions of Windows

If you would like to submit a bug report, please visit:

http://bugreport.java.com/bugreport/crash.jsp

The crash happened outside the Java Virtual Machine in native code.

See problematic frame for where to report the bug.

--------------- S U M M A R Y ------------

Command Line: -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:52074,suspend=y,server=n -javaagent:C:\Users\rhqua60.IdeaIC2018.1\system\captureAgent\debugger-agent.jar=file:/C:/Users/rhqua60/AppData/Local/Temp/capture.props -Dfile.encoding=UTF-8 com.Rexnord.App 1 com4 1 1

Host: Intel(R) Core(TM) i7-7600U CPU @ 2.80GHz, 4 cores, 15G, Windows 10 , 64 bit Build 16299 (10.0.16299.15)
Time: Fri Jun 22 11:43:12 2018 Central Daylight Time elapsed time: 0 seconds (0d 0h 0m 0s)

--------------- T H R E A D ---------------

Current thread (0x0000020c90753800): JavaThread "main" [_thread_in_native, id=12968, stack(0x0000005738d00000,0x0000005738e00000)]

Stack: [0x0000005738d00000,0x0000005738e00000], sp=0x0000005738dff020, free space=1020k
Native frames: (J=compiled Java code, j=interpreted, Vv=VM code, C=native code)
C [jSSC-2.8_x86_64.dll+0xb5db]

Java frames: (J=compiled Java code, j=interpreted, Vv=VM code)
j jssc.SerialNativeInterface.openPort(Ljava/lang/String;Z)J+0
j jssc.SerialPort.openPort()Z+65
j com.intelligt.modbus.jlibmodbus.serial.SerialPortJSSC.open()V+4
j com.intelligt.modbus.jlibmodbus.net.ModbusConnectionSerial.openImpl()V+11
j com.intelligt.modbus.jlibmodbus.net.ModbusConnection.open()V+1
j com.intelligt.modbus.jlibmodbus.master.ModbusMaster.connectImpl()V+4
j com.intelligt.modbus.jlibmodbus.master.ModbusMaster.connect()V+8
j com.Rexnord.App.main([Ljava/lang/String;)V+265
v ~StubRoutines::call_stub

siginfo: EXCEPTION_ACCESS_VIOLATION (0xc0000005), reading address 0xffffffff8e781aac

Register to memory mapping:

RIP=0x000000007110b5db jSSC-2.8_x86_64.dll
RAX=0xffffffff8e781aac is an unknown value
RBX=0x0000005738dff090 is pointing into the stack for thread: 0x0000020c90753800
RCX=0x00007ffb90fc0024 ntdll.dll
RDX=0x0000000000000000 is an unknown value
RSP=0x0000005738dff020 is pointing into the stack for thread: 0x0000020c90753800
RBP=0x0000005738dff1a0 is pointing into the stack for thread: 0x0000020c90753800
RSI=0x0000020c90753a70 is an unknown value
RDI=0x00000000000005bc is an unknown value
R8 =0x0000005738dfef18 is pointing into the stack for thread: 0x0000020c90753800
R9 =0x0000005738dff010 is pointing into the stack for thread: 0x0000020c90753800
R10=0x0000000000000000 is an unknown value
R11=0x0000000000000246 is an unknown value
R12=0x0000005738dff260 is pointing into the stack for thread: 0x0000020c90753800
R13=0x0000020cb7725990 is an unknown value
R14=0x0000005738dff150 is pointing into the stack for thread: 0x0000020c90753800
R15=0x0000020c90753800 is a thread

Registers:
RAX=0xffffffff8e781aac, RBX=0x0000005738dff090, RCX=0x00007ffb90fc0024, RDX=0x0000000000000000
RSP=0x0000005738dff020, RBP=0x0000005738dff1a0, RSI=0x0000020c90753a70, RDI=0x00000000000005bc
R8 =0x0000005738dfef18, R9 =0x0000005738dff010, R10=0x0000000000000000, R11=0x0000000000000246
R12=0x0000005738dff260, R13=0x0000020cb7725990, R14=0x0000005738dff150, R15=0x0000020c90753800
RIP=0x000000007110b5db, EFLAGS=0x0000000000010206

Regarding Jlibmodbus licence

Dears,

We are from Samsung, We would like to use jlibmodbus for our purpose. we have few questions to use this lib.

  1. is that lib is part of Apache or LGPL. Becoz ur sourceforge ., it is showing LGPL but, git hub showz as Apache., pls confirm it.

  2. we want to know jserielmodbus package, is that also part of Apache or GPL 3.0

  3. If we are planning to use commercial purpose, i hope, if it s Apace, then it willbe good.

  4. what is procedure to cobtribute for open source ?

Regards,
Muthu

Reduce data copying operations number

By now every time when you request something from a slave this produces many operations of data copying. It would be nice to reduce the data copying operations number as far as it's possible.

jserialcomm 2.6.2 problem

on jserialcomm 2.6.2, have problem with SetComPortParameter.

My java code
`/**
* Open Serial Port for communication
* @param serialname : serial port name
* @param baudrate : baud rate, typically 4800, 9600, 144400, 19200, 38400, 57600, 115200
* @param databit : data bit length , typically 8
* @param stopbit : typically 1
* @param parity : 0 = None, 1 = Odd, 2 = Even, 3 = Mark, 4 = Space
* @return true if success
*/
public boolean Open(String serialname, int baudrate, int databit, int stopbit, int parity) {
sp = new SerialParameters();

	sp.setDataBits(databit);
	sp.setDevice(serialname);
	sp.setStopBits(stopbit);
	sp.setBaudRate(BaudRate.getBaudRate(baudrate));
	sp.setParity(Parity.getParity(parity));
	
	SerialUtils.setSerialPortFactoryJSerialComm();
	
	try {
		
		modbus = ModbusSlaveFactory.createModbusSlaveRTU(sp);
		
		modbus.addListener(listener);
		
		modbus.listen();
		return true;
	} catch (SerialPortException e) {
		raise_log("Open failed, Msg : "+e.getMessage());
		return false;
	} catch (ModbusIOException e) {
		raise_log("Modbus Listen failed, Msg : "+e.getMessage());
		return false;
	}
}`

Log :
java.lang.NoSuchMethodError: com.fazecast.jSerialComm.SerialPort.setComPortParameters(IIII)V at com.intelligt.modbus.jlibmodbus.serial.SerialPortJSerialComm.open(SerialPortJSerialComm.java:71) at com.intelligt.modbus.jlibmodbus.net.ModbusConnectionSerial.openImpl(ModbusConnectionSerial.java:60) at com.intelligt.modbus.jlibmodbus.net.ModbusConnection.open(ModbusConnection.java:45) at com.intelligt.modbus.jlibmodbus.slave.RequestHandlerSerial.run(RequestHandlerSerial.java:51) at java.lang.Thread.run(Thread.java:748)

Dependencies issues with Android things support that affect PC based projects

Two Issues

  1. Version 1.2.9.7 breaks SBT build, I need to manually add below for SBT to download the package
    "Android Google Maven2 Repository" at "https://maven.google.com/"

    I don't need Android, I build for Windows and Linux and Mac.

  2. After adding Android Google Maven repo, it downloads android thing jars, but the program crash at runtime due to poor selection of Android library on Windows.

I see https://github.com/kochedykov/jlibmodbus/blob/master/src/com/intelligt/modbus/jlibmodbus/serial/SerialUtils.java source code,

static private Set<ValidatorSerialPortFactory> validatorSet = new TreeSet<ValidatorSerialPortFactory>();

    static {
        registerSerialPortFactory("com.google.android.things.AndroidThings", SerialPortFactoryAT.class.getCanonicalName());
        registerSerialPortFactory("com.fazecast.jSerialComm.SerialPort", SerialPortFactoryJSerialComm.class.getCanonicalName());
        registerSerialPortFactory("jssc.SerialPort", SerialPortFactoryJSSC.class.getCanonicalName());
        registerSerialPortFactory("purejavacomm.PureJavaComm", SerialPortFactoryPJC.class.getCanonicalName());
        registerSerialPortFactory("gnu.io.RXTXVersion", SerialPortFactoryRXTX.class.getCanonicalName());
    }

Can you provide a public method where we could remove not wanted registerSerialPortFactory? Kindly provide option to remove unwanted serial port options, especially Android.

Version 1.2.9.5 works great, thanks for the great work.

Documentation?

I know this is probably an unwelcome question, but do you have any instructions for a beginner?

Invalid checksum issue fixed for RTU frame is also present in ASCII framer

The issue is same as #11, only for ASCII framer instead of RTU. If checksum happen to be 0, you get an exception raised

Caused by: com.intelligt.modbus.jlibmodbus.exception.ModbusChecksumException: checksum error: received 0, calculated 0
	at com.intelligt.modbus.jlibmodbus.net.stream.InputStreamASCII.frameCheck(InputStreamASCII.java:60)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransportSerial.read(ModbusTransportSerial.java:46)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransport.readMessage(ModbusTransport.java:69)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransport.readResponse(ModbusTransport.java:64)
	at com.intelligt.modbus.jlibmodbus.master.ModbusMaster.readResponse(ModbusMaster.java:111)
	at com.intelligt.modbus.jlibmodbus.master.ModbusMaster.processRequest(ModbusMaster.java:134)
	at com.intelligt.modbus.jlibmodbus.master.ModbusMaster.readHoldingRegisters(ModbusMaster.java:193)

problem building jar file

Some problems were encountered while building the effective model for com.intelligt.modbus:jlibmodbus:jar:1.2.9.7
'dependencies.dependency.systemPath' for javax.comm:comm:jar should not point at files within the project directory, ${project.basedir}/lib/comm.jar will be unresolvable by dependent projects @ line 53, column 25
'dependencies.dependency.systemPath' for javax.comm:comm:jar refers to a non-existing file C:\Users\admin\Downloads\jlibmodbus\lib\comm.jar @ line 53, column 25

It is highly recommended to fix these problems because they threaten the stability of your build.

For this reason, future Maven versions might no longer support building such malformed projects.

Inspecting build with total of 1 modules...
Installing Nexus Staging features:
... total of 1 executions of maven-deploy-plugin replaced with nexus-staging-maven-plugin


Building JLibModbus 1.2.9.7

The POM for com.google.android.things:androidthings:jar:0.8 is missing, no dependency information available

BUILD FAILURE

Total time: 1.161s
Finished at: Wed Oct 24 12:47:37 EEST 2018
Final Memory: 9M/155M

Failed to execute goal on project jlibmodbus: Could not resolve dependencies for project com.intelligt.modbus:jlibmodbus:jar:1.2.9.7: The following artifacts could not be resolved: javax.comm:comm:jar:2.0.3, com.google.android.things:androidthings:jar:0.8: Could not find artifact javax.comm:comm:jar:2.0.3 at specified path C:\Users\admin\Downloads\jlibmodbus\lib\comm.jar -> [Help 1]

To see the full stack trace of the errors, re-run Maven with the -e switch.
Re-run Maven using the -X switch to enable full debug logging.

For more information about the errors and possible solutions, please read the following articles:
[Help 1] http://cwiki.apache.org/confluence/display/MAVEN/DependencyResolutionException

incorrect logic on zero CRC

if crc16 checksum is zero, exception thrown, but checksum is correct
logs:
INFO: Frame sent: F70400000010E550
INFO: Frame recv: F70420FFE2FFF0030C008C008404C004CC043A0007000C013D000C00040A3400020016F816
INFO: Frame sent: F70400000010E550
INFO: Frame recv: F70420FFE2FFF0030E008B008404C004CC043A0007000C013D000C00040A3400020016AD3D
INFO: Frame sent: F70400000010E550
INFO: Frame recv: F70420FFE3FFF10315008B008304C004CC043A0007000C0142000C00040A34000200160000
com.invertor.modbus.exception.ModbusChecksumException: checksum error: received 0, calculated 0
at com.invertor.modbus.net.stream.InputStreamRTU.frameCheck(InputStreamRTU.java:44)
at com.invertor.modbus.net.transport.ModbusTransportSerial.read(ModbusTransportSerial.java:50)
at com.invertor.modbus.net.transport.ModbusTransport.readMessage(ModbusTransport.java:60)
at com.invertor.modbus.net.transport.ModbusTransport.readResponse(ModbusTransport.java:55)
at com.invertor.modbus.ModbusMaster.readResponse(ModbusMaster.java:110)
at com.invertor.modbus.ModbusMaster.processRequest(ModbusMaster.java:135)
at com.invertor.modbus.ModbusMaster.readInputRegisters(ModbusMaster.java:208)

ModbusSlaveRTU w/ jssc incorrectly times out on large request transaction size

ModbusSlaveRTU constructor sets the timeout to 10 * the symbol rate, this is hardcoded. However with the JSSC implementation, the SerialPort.waitBytesWithTimeout is used to read the entire expected transaction on a call to SerialPort.read(byte[] b, ...)

The desired timeout was for a symbol but JSSC wants a timeout for the entire frame (amount to be read). Thus, for larger frames, or slow baud rates, JSSC will throw a timeout exception.

Issue is fixed by increasing the timeout in ModbusSlaveRTU to the default 1 second timeout.

Setting timeout for jSerialComm don't work because of TIMEOUT_NONBLOCKING flag

Hello

I am using in my project jSerialComm and tried to use this also for the modbus communication:

SerialPortFactoryJSerialComm factory = new SerialPortFactoryJSerialComm();
SerialUtils.setSerialPortFactory(factory);

But I get everytime a read timeout error
com.fazecast.jSerialComm.SerialPortTimeoutException: The read operation timed out before any data was returned.

Looking in the source code I found this in SerialPortJSerialComm:

    @Override
    public void open() throws SerialPortException {
        SerialParameters sp = getSerialParameters();
        port = com.fazecast.jSerialComm.SerialPort.getCommPort(sp.getDevice());
        port.openPort();

        port.setComPortParameters(sp.getBaudRate(), sp.getDataBits(), sp.getStopBits(), sp.getParity().getValue());
        port.setFlowControl(com.fazecast.jSerialComm.SerialPort.FLOW_CONTROL_DISABLED);

        in = port.getInputStream();
        out = port.getOutputStream();

        port.setComPortTimeouts(com.fazecast.jSerialComm.SerialPort.TIMEOUT_READ_BLOCKING, getReadTimeout(), 0);

    }

    @Override
    public void setReadTimeout(int readTimeout) {
        super.setReadTimeout(readTimeout);

        if (isOpened()) {
            port.setComPortTimeouts(com.fazecast.jSerialComm.SerialPort.TIMEOUT_NONBLOCKING, getReadTimeout(), getReadTimeout());
        }
    }

For me it was not clear why in the first setting TIMEOUT_READ_BLOCKING was used and in the second TIMEOUT_NONBLOCKING.
So I change the TIMEOUT_NONBLOCKING to TIMEOUT_READ_BLOCKING.
This changes working for me very fine.

    @Override
    public void open() throws SerialPortException {
        SerialParameters sp = getSerialParameters();
        port = com.fazecast.jSerialComm.SerialPort.getCommPort(sp.getDevice());
        port.openPort();

        port.setComPortParameters(sp.getBaudRate(), sp.getDataBits(), sp.getStopBits(), sp.getParity().getValue());
        port.setFlowControl(com.fazecast.jSerialComm.SerialPort.FLOW_CONTROL_DISABLED);

        in = port.getInputStream();
        out = port.getOutputStream();

        port.setComPortTimeouts(com.fazecast.jSerialComm.SerialPort.TIMEOUT_READ_BLOCKING, getReadTimeout(), getReadTimeout());

    }

    @Override
    public void setReadTimeout(int readTimeout) {
        super.setReadTimeout(readTimeout);

        if (isOpened()) {
            port.setComPortTimeouts(com.fazecast.jSerialComm.SerialPort.TIMEOUT_READ_BLOCKING, getReadTimeout(), getReadTimeout());
        }
    }

How to request Preset Multiple Register that is Write Multiple Register(Function Code:16) using RTU ? Can you provide any example or test class ?

Here how I am using it but don't know whether its correct and how to check response for the same. Please let me know if I am missing something in below code.

WriteMultipleRegistersRequest multipleRegistersRequest = null;
            WriteMultipleRegistersResponse multipleRegistersResponse = null;
            SerialUtils.setSerialPortFactory(new SerialPortFactoryJSerialComm());
            
            SerialParameters serialParameters = new SerialParameters();
            serialParameters.setBaudRate(SerialPort.BaudRate.BAUD_RATE_9600);
            serialParameters.setParity(SerialPort.Parity.NONE);
            serialParameters.setDataBits(8);
            serialParameters.setStopBits(1);
            serialParameters.setDevice("COM5");
         try {   
            ModbusMaster m = ModbusMasterFactory.createModbusMasterRTU(serialParameters);
            m.connect();
             System.out.println("Connected");
            multipleRegistersRequest = new WriteMultipleRegistersRequest();
            multipleRegistersRequest.setServerAddress(1);//ModbusAddress of Slave device to be read
            multipleRegistersRequest.setStartAddress(458); // Start Address
            multipleRegistersRequest.setRegisters(new int[]{14,28,65,200}); //Values to write at different registers
           
            m.setResponseTimeout(500);
            m.processRequest(multipleRegistersRequest);

            multipleRegistersResponse = (WriteMultipleRegistersResponse) multipleRegistersRequest.getResponse();
             System.out.println("<> "+multipleRegistersResponse.getValue());
             System.out.println("<> "+multipleRegistersResponse.toString());
            
        } catch (SerialPortException ex) {
            Logger.getLogger(JLibModbusTestClass.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ModbusIOException ex) {
            Logger.getLogger(JLibModbusTestClass.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ModbusNumberException ex) {
            Logger.getLogger(JLibModbusTestClass.class.getName()).log(Level.SEVERE, null, ex);
        }

I have updated my code.But Still I am getting error as following

com.intelligt.modbus.jlibmodbus.exception.ModbusIOException: java.io.IOException: com.fazecast.jSerialComm.SerialPortTimeoutException: The read operation timed out before any data was returned.
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransportSerial.read(ModbusTransportSerial.java:49)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransport.readMessage(ModbusTransport.java:69)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransport.readResponse(ModbusTransport.java:64)
	at com.intelligt.modbus.jlibmodbus.master.ModbusMaster.readResponse(ModbusMaster.java:111)
	at com.intelligt.modbus.jlibmodbus.master.ModbusMaster.processRequest(ModbusMaster.java:134)
	at com.importexportutility.jlibmodbustest.JLibModbusTestClass.main(JLibModbusTestClass.java:52)
Caused by: java.io.IOException: com.fazecast.jSerialComm.SerialPortTimeoutException: The read operation timed out before any data was returned.
	at com.intelligt.modbus.jlibmodbus.serial.SerialPortJSerialComm.read(SerialPortJSerialComm.java:100)
	at com.intelligt.modbus.jlibmodbus.serial.SerialPort$2.read(SerialPort.java:77)
	at com.intelligt.modbus.jlibmodbus.net.stream.base.LoggingInputStream.read(LoggingInputStream.java:52)
	at com.intelligt.modbus.jlibmodbus.net.stream.InputStreamRTU.read(InputStreamRTU.java:55)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransport.createMessage(ModbusTransport.java:51)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransportSerial.read(ModbusTransportSerial.java:45)
	... 5 more
Caused by: com.fazecast.jSerialComm.SerialPortTimeoutException: The read operation timed out before any data was returned.
	at com.fazecast.jSerialComm.SerialPort$SerialPortInputStream.read(SerialPort.java:1328)
	at com.intelligt.modbus.jlibmodbus.serial.SerialPortJSerialComm.read(SerialPortJSerialComm.java:98)
	... 10 more


Reading the response of the "ReadDeviceIdentificationRequest"

How can I read the response of the request made with ReadDeviceIdentificationRequest object to a modbus slave that is actually giving a response to this request?

I tried to cast the ModbusResponse object to EncapsulatedInterfaceTransportResponse object but cannot withdraw anything substantial that is related to the very response itself.

Is there a special way to get the value of the response, like a ReadDeviceIdentificationResponse object with a getter methods like "getVendorName()" and more?

Everything else seems to be in order. Cheers.

ModbusMaster disconnectimpl()

Hello!

I am using your library for modbus communication. I updated library to the newest version and i had seen that disconnectimpl(); has a wrong implementation. We cannot now close serial port to use it to other purposes.

Just see and compare with previous version of ModbusMaster.java file:

    /**
     * this method allows you to implement your own behavior of disconnect method.
     *
     * @throws ModbusIOException
     */
    protected void disconnectImpl() throws ModbusIOException {
        getConnection().open();
    }

java.net.SocketTimeoutException: Read timed out

The idea is to make the server listening and the clients would connect to them.
But not as a Modbus TCP client, as a normal TCP client, so the server could read the clients (act like Modbus Master) rather than read by clients.
Maybe the idea totally wrong.

The test code:

    @Test
    public void testConnection() throws IOException, ModbusNumberException, ModbusProtocolException, ModbusIOException {
        ServerSocket serverSocket = new ServerSocket(3333);
        Socket client = serverSocket.accept();
        ModbusTranslator modbusTranslator = new ModbusTranslator(client);
        modbusTranslator.connect();
        modbusTranslator.setResponseTimeout(3000);
        modbusTranslator.writeSingleRegister(1,1,1);
    }

Which will issue a SocketTimeoutException when running the test.
Using hercules-setup-utility from https://www.hw-group.com/software/hercules-setup-utility
to simulate a client socket.

  1. The network is fine when using client.getOutputStream() and client.getInputStream();
  2. The error log is almost same if change last line to modbusTranslator.readHoldingRegisters(1,1,1);
  3. The ModbusTranslator implements FrameEventListenerList with a custom EmbeddedConnection which extends ModbusConnection

The mainly different from your ModbusMasterConnection is it get the socket instead from init from tcp parameters.

    @Override
    protected void openImpl() {
        if (!isOpened()) {
            if (socket.isConnected()) {
                try {
                    transport = ModbusTransportFactory.createTCP(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
                setReadTimeout(getReadTimeout());
            }
        }
    }
com.intelligt.modbus.jlibmodbus.exception.ModbusIOException: java.net.SocketTimeoutException: Read timed out

	at com.intelligt.modbus.jlibmodbus.tcp.TcpAduHeader.read(TcpAduHeader.java:103)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransportTCP.read(ModbusTransportTCP.java:50)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransport.readMessage(ModbusTransport.java:69)
	at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransport.readResponse(ModbusTransport.java:64)
	at dems.server.ModbusTranslator.readResponse(ModbusTranslator.java:80)
	at dems.server.ModbusTranslator.processRequest(ModbusTranslator.java:100)
	at dems.server.ModbusTranslator.writeSingleRegister(ModbusTranslator.java:264)
	at dems.server.ModbusTranslatorTest.testConnection(ModbusTranslatorTest.java:19)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:564)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
	at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
	at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:47)
	at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
	at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.net.SocketTimeoutException: Read timed out
	at java.base/java.net.SocketInputStream.socketRead0(Native Method)
	at java.base/java.net.SocketInputStream.socketRead(SocketInputStream.java:116)
	at java.base/java.net.SocketInputStream.read(SocketInputStream.java:171)
	at java.base/java.net.SocketInputStream.read(SocketInputStream.java:141)
	at java.base/java.io.BufferedInputStream.fill(BufferedInputStream.java:246)
	at java.base/java.io.BufferedInputStream.read1(BufferedInputStream.java:286)
	at java.base/java.io.BufferedInputStream.read(BufferedInputStream.java:345)
	at com.intelligt.modbus.jlibmodbus.net.stream.InputStreamTCP$1.read(InputStreamTCP.java:55)
	at com.intelligt.modbus.jlibmodbus.net.stream.base.LoggingInputStream.read(LoggingInputStream.java:61)
	at com.intelligt.modbus.jlibmodbus.net.stream.base.ModbusInputStream.read(ModbusInputStream.java:50)
	at com.intelligt.modbus.jlibmodbus.tcp.TcpAduHeader.read(TcpAduHeader.java:91)
	... 29 more

Disconnected from the target VM, address: '127.0.0.1:53170', transport: 'socket'

Process finished with exit code -1

Any help would be appreciated.

Setting negative Integer in ModbusHoldingRegisters causes IllegalDataValueException

I have a Modbus Slave that uses a DataHolder which has a number of HoldingRegisters.
When i try to set a negative integer value with the function:
this.slave.getDataHolder().getHoldingRegisters().set(offset, intValue);
the ModbusHoldingRegisters.checkValue() method throws an IllegalDataValueException.

I think that the Modbus.checkRegisterValue() method should check for a range with min value=-32768 (minimum signed 16-bit integer value) instead of 0.

ModbusNumberException for valid value

I encountered a strange error which seemed like it cannot occur. This is in version 1.2.9.2. Stack trace below. I get a ModbusNumberException for value "4112". However in WriteSingleRegisterResponse.setValue, the value is first cast to a short and and'ed with 0xffff. Then the checkValue makes sure its within the range 0 to 65535. Clearly 4112 passes that check so I can't understand why the exception is being thrown.

com.intelligt.modbus.jlibmodbus.exception.ModbusNumberException: Error in register value : 4112 at com.intelligt.modbus.jlibmodbus.msg.response.WriteSingleRegisterResponse.setValue(WriteSingleRegisterResponse.java:71) at com.intelligt.modbus.jlibmodbus.msg.response.WriteSingleRegisterResponse.readValue(WriteSingleRegisterResponse.java:44) at com.intelligt.modbus.jlibmodbus.msg.base.AbstractWriteResponse.readResponse(AbstractWriteResponse.java:46) at com.intelligt.modbus.jlibmodbus.msg.base.ModbusResponse.readPDU(ModbusResponse.java:65) at com.intelligt.modbus.jlibmodbus.msg.base.ModbusMessage.read(ModbusMessage.java:54) at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransport.createMessage(ModbusTransport.java:55) at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransportSerial.read(ModbusTransportSerial.java:45) at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransport.readMessage(ModbusTransport.java:69) at com.intelligt.modbus.jlibmodbus.net.transport.ModbusTransport.readResponse(ModbusTransport.java:64) at com.intelligt.modbus.jlibmodbus.master.ModbusMaster.readResponse(ModbusMaster.java:111) at com.intelligt.modbus.jlibmodbus.master.ModbusMaster.processRequest(ModbusMaster.java:134)

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.