AdvancedClimateSystems / uModbus

Python implementation of the Modbus protocol.
Mozilla Public License 2.0
213 stars 83 forks source link

ReadHoldingRegisters dosen't support Long/Float data type? #61

Closed lxcsmallcity closed 6 years ago

lxcsmallcity commented 6 years ago

ReadHoldingRegisters dosen't support Long/Float data type?

And,Float data type contained: "AB CD","CD AB" data format

OrangeTux commented 6 years ago

ReadHoldingRegisters dosen't support Long/Float data type?

No, uModbus only supports 16 bits integers. Those are unsigned by default, but can be signed. Read here for more on that.

If you want read or write floats according to IEEE 754 you need to split the float into 2 16 bit numbers.

And,Float data type contained: "AB CD","CD AB" data format

I'm not sure what you mean by this?

lxcsmallcity commented 6 years ago

Yes,I want read or write floats according to IEEE 754.Like "electric instrument" devices etc.

OrangeTux commented 6 years ago

Well, to write binary32 number to 2 registers you can do this::

import struct

f = -123.456

# IEE 754 representation of f.
binary32 = struct.pack('>d', f)

high_byte, low_byte = struct.unpack('>HH', binary32)

Now you can write the high and low byte on 2 separate registers.

To read 2 registers and combine them back to a float you can do this:


import struct
high_byte = 49910
low_byte = 59769

# f is -123.45600128173828
f = struct.unpack('>f', struct.pack('>H', high_byte) + struct.pack('>H', low_byte)[0]
lxcsmallcity commented 6 years ago

OK,Thank you very much. Have you think about add the function into next version? Like "modbus_tk" library,it can be input parameter “ data_format='>f' ”

OrangeTux commented 6 years ago

No I'm not considering this right now. For now I think the increase of API complexity doesn't weight out the gains in functionality.

And as I demonstrated, it can easily be done with in the existing API.