Cloud-Automation / node-modbus

Modbus TCP Client/Server implementation for Node.JS
471 stars 175 forks source link

ReadCoils Function implements wrong addressing scheme in server #44

Closed psorowka closed 8 years ago

psorowka commented 8 years ago

Hi,

we have stumbled upon the following issue. When reading coils, the LSB of the answer is required to equal the start address specified in the command. See the following quote from the spec:

The LSB of the first data byte contains the output addressed in the query. The other coils follow toward the high order end of this byte, and from low order to high order in subsequent bytes.

(from http://www.modbus.org/docs/Modbus_Application_Protocol_V1_1b3.pdf Chapter 6)

However, the current server implementation seems to align the coils on a fixed "grid" starting at multiples of address 8.

So e.g. when calling readCoils(5,1) (and assuming that the value at address 5 is true) the expected result would be:

[true, false, false, false, false, false, false, false] // 00000001

but the actual result currently is

[false, false, false, false, false, true, false, false] // 00100000

I figure the issue is the following line https://github.com/Cloud-Automation/node-modbus/blob/master/src/handler/server/ReadCoils.js#L55

val += mem.readUInt8(Math.floor(i / 8)) &  Math.pow(2, i % 8);

which should probably be something like

if(mem.readUInt8(Math.floor(i / 8)) & Math.pow(2, i % 8)) {
  val += 1 << ( j % 8)
}

d'accord? :-) or am I missing something? I can create a PR.

PS: that is the same for discrete inputs.