0

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

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

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

如何调节数组 PQV 的负元素以使 pymodbus 可以接受?

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

1 回答 1

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
>>>

希望这可以帮助。

于 2019-04-14T05:52:04.777 回答