在写入数据存储之前,浮点数将以 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
>>>
希望这可以帮助。