steveohara / j2mod

Enhanced Modbus library implemented in the Java programming language
Apache License 2.0
267 stars 111 forks source link

Length of ReadWriteMultipleResponse indicates 1 byte too much? #31

Closed elasticoder closed 7 years ago

elasticoder commented 7 years ago

Compared to the modbusTCP specs listed at the website http://www.modbus-ida.org the respons of a functioncall 0x17 contains the following information:

Function code Byte count 2bytes for each register

When reading 5 registers, the bytecount shows 11 instead of 10.. In the code I can see +1 added everywere. Is this actually correct?

byteCount = registers.length * 2 + 1; (what is the +1 doing here?)

steveohara commented 7 years ago

I suspect it's the slave/unit address. A Modbus TCP message starts with an MBAP header that has a one byte slave address or unit ID. Here is a nice reference; http://www.simplymodbus.ca/TCP.htm

elasticoder commented 7 years ago

Perhaps I wasn't clear.

Here is the byte-string I send to the modbus Slave: 0x00, 0x00, 0x00, 0x00, 0x0D, 0x0F, 0x17, 0x00, 0x00, 0x00, 0x05, 0x08, 0x00, 0x00, 0x01, 0x02, 0x55, 0x55 It writes one register and wants to read 5 registers, hence the function code 0x17.

I receive the following bytestring back:

0x00, 0x00, 0x00, 0x00, 0x00, 0x0D, 0x0F, 0x17, 0x0B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00

I suspect the (in bold) 0x0B should be 0x0A as it indicates the number of bytes to read.

steveohara commented 7 years ago

Oh ok, I understand now. Yes, it looks like a bug to me - looking at the implementations of all the other function codes, it appears that it is also wrong for function code 4. (perhaps this is the origin of the problem i.e. the developer cut & pasted from here) However, this interface is unit tested using ModPoll and this doesn't barf up so I'm wondering why that is.

steveohara commented 7 years ago

I've made the changes and built them into 2.3.1-SNAPSHOT. Could you give it a try and confirm it's now working it correctly.

elasticoder commented 7 years ago

I can confirm both changes. Be carefull though, both snapshot changes alter the same file overriding the change from the other again if you replace the whole contents of the file. (As I did)

Thanks!

steveohara commented 7 years ago

Merged into 2.3.1