pymodbus输入寄存器中的负数应如何表示?

时间:2019-04-13 06:55:25

标签: python modbus pymodbus

我想给pymodbus异步服务器中的输入寄存器分配负数。我有一个名为PQV的5元素数组,其中包含数量级为0到300的数字,但是某些元素是负数

PQV=[145, -210, 54, 187, -10]

我使用下面的代码将PQV分配给从地址0开始的输入寄存器(寄存器4)。我尝试将65536添加到所有负数,但这没有用。

如何将PQV数组的负元素设置为pymodbus可接受?

context[slave_id].setValues(4, 0, PQV)

1 个答案:

答案 0 :(得分:0)

浮点数将以IEEE-754十六进制格式表示,然后再写入数据存储区。您可以执行以下操作来实现它。

# Import BinaryPayloadBuilder and Endian
from pymodbus.payload import BinaryPayloadBuilder, Endian
# Create the builder, Use the correct endians for word and byte
builder = BinaryPayloadBuilder(byteorder=Endian.Big, wordorder=Endian.Big)

在您的更新功能中

busvoltages = [120.0, 501.3, -65.2, 140.3, -202.4]
builder.reset() # Reset Old entries
for vol in busvoltages:
    builder.add_32bit_float(vol)
payload = builder.to_registers()   # Convert to int values
# payload will have these values [17136, 0, 17402, 42598, 49794, 26214, 17164, 19661, 49994, 26214]
context[slave_id].setValues(2, 0, payload)  # write to datablock

当您读回值时,您将返回原始int值。您将必须使用BinaryPayloadDecoder

将它们转换回浮点数
>>> from pymodbus.payload import BinaryPayloadDecoder, Endian
>>> r = client.read_input_registers(0, 10, unit=1)
# Use the same byte and wordorders
>>> d = BinaryPayloadDecoder.fromRegisters(r.registers, byteorder=Endian.Big, wordorder=Endian.Big)
>>> d.decode_32bit_float()
120.0
>>> d.decode_32bit_float()
501.29998779296875
>>> d.decode_32bit_float()
-65.19999694824219
>>> d.decode_32bit_float()
140.3000030517578
>>> d.decode_32bit_float()
-202.39999389648438
>>> # Further reads after the registers are exhausted will throw struct error
>>> d.decode_32bit_float()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/sanjay/.virtualenvs/be3/lib/python3.6/site-packages/pymodbus/payload.py", line 440, in decode_32bit_float
    handle = self._unpack_words(fstring, handle)
  File "/Users/sanjay/.virtualenvs/be3/lib/python3.6/site-packages/pymodbus/payload.py", line 336, in _unpack_words
    handle = unpack(up, handle)
struct.error: unpack requires a buffer of 4 bytes
>>>

希望这会有所帮助。