我使用pymodbus读取和解码float_32值。
之前,我使用以下代码对它进行了简单的解码:
from pymodbus.client.sync import ModbusTcpClient
from pymodbus.constants import Endian
from pymodbus.payload import BinaryPayloadDecoder
cli = ModbusTcpClient('an-IP')
cli.connect()
req = cli.read_holding_registers(<hex-address>, count=4)
dec = BinaryPayloadDecoder.fromRegisters(req.registers, endian=Endian.Little)
print(dec.decode_32bit_float())
但是最近我发生了这个错误:
TypeError: fromRegisters() got an unexpected keyword argument 'endian'
[更新]
我认为pymodbus
的较新版本已被修改(endian
参数已被弃用):
A reference:看起来参数已更改,但文档未更改
然后我将这一行更改如下:
dec = BinaryPayloadDecoder.fromRegisters(
req.registers,
byteorder=Endian.Big,
wordorder=Endian.Little)
现在,我想检查pymodbus版本以了解必须使用哪个版本的解码。
答案 0 :(得分:2)
我发现了一个绕过pymodbus
版本来解码float_32值以处理不同版本的解码功能的技巧:
try:
'''For pymodbus 1.3.2 and older version.'''
dec = BinaryPayloadDecoder.fromRegisters(req.registers,
endian=Endian.Little)
except:
'''For pymodbus 1.4.0 and newer version.'''
dec = BinaryPayloadDecoder.fromRegisters(req.registers,
byteorder=Endian.Big,
wordorder=Endian.Little)
或:
import inspect
if 'endian' in inspect.getargspec(BinaryPayloadDecoder.fromRegisters)[0]:
'''For pymodbus 1.3.2 and older version.'''
dec = BinaryPayloadDecoder.fromRegisters(
req.registers,
endian=Endian.Little)
else:
'''For pymodbus 1.4.0 and newer version.'''
dec = BinaryPayloadDecoder.fromRegisters(
req.registers,
byteorder=Endian.Big,
wordorder=Endian.Little)
[注意]:
您还可以通过以下方式检查PyPi软件包的版本:pip show <pkg-name>