Cloud-Automation / node-modbus

Modbus TCP Client/Server implementation for Node.JS
465 stars 174 forks source link

readHoldingRegisters - float number expected #228

Closed vilelam closed 5 years ago

vilelam commented 5 years ago

Dear jsmodbus experts, This might be a recurrent question, but I'm still not able to make it work. I'm accessing a TCP Modbus server to read the register 126 (modbus number 40126), which is a signed 16 bit binary number. With the following code I'm getting the results below in ReadHoldingRegistersResponseBody. I'm receiving 10 while expecting to see 10.1. How can I make it return a float number instead of an int? Thanks in advance, Marcos

socket.on("connect", function() {
  client
    .readHoldingRegisters(125,1)
    .then(function(resp) {
      console.log(resp.response._body);
      socket.end();
    })
    .catch(function() {
      console.error(
        require("util").inspect(arguments, {
          depth: null
        })
      );
      socket.end();
    });
});

Result:

ReadHoldingRegistersResponseBody {
  _fc: 3,
  _byteCount: 2,
  _values: [ 10 ],
  _bufferLength: 4,
  _valuesAsArray: [ 10 ],
  _valuesAsBuffer: <Buffer 00 0a> }
stefanpoeter commented 5 years ago

First of all you need to understand that modbus transfers registers of 16bit size. Most of the time floating point numbers are represented either as 32bit or 64bit size buffers. So if you want to get a floating point you have to at least catch two registers for example readHoldingRegisters(125, 2) and the work with the response buffer response.valuesAsBuffer.readFloat32BE(0).

cwg999 commented 5 years ago

In case you can't find anything for readFloat32BE https://nodejs.org/api/buffer.html#buffer_buf_readfloatbe_offset buffer.readFloatBE(offset), buffer.readFloatLE(offset), etc.

vilelam commented 5 years ago

@stefanpoeter @cwg999 - thanks for your response. I've studied this topic and now I understand what you've mentioned that modbus only transfers registers of 16bit size and if a float is required at least I will need 2 register os 16bits. I contacted the development team responsible for the modbus server I'm accessing and they told me that the decimal part of the numbers is not available in the modbus server. So I can't do much in this case, but it helped me to learn more. thanks again, marcos.

cwg999 commented 5 years ago

No problem! You can probably close the issue since it is not an issue with this project, but your modbus server :)